Changeset - 54687aa00724
rhodecode/controllers/admin/notifications.py
Show inline comments
 
import logging
 
import traceback
 

	
 
from pylons import tmpl_context as c
 
from pylons import tmpl_context as c, url
 

	
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.model.db import Notification
 

	
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.lib.auth import LoginRequired
 
from rhodecode.lib import helpers as h
 
from rhodecode.model.meta import Session
 
from pylons.controllers.util import redirect
 

	
 
log = logging.getLogger(__name__)
 

	
 
class NotificationsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('notification', 'notifications', controller='_admin/notifications', 
 
    #         path_prefix='/_admin', name_prefix='_admin_')
 

	
 
    @LoginRequired()
 
    def __before__(self):
 
@@ -48,37 +51,52 @@ class NotificationsController(BaseContro
 
        #           method='put')
 
        # url('notification', notification_id=ID)
 

	
 
    def delete(self, notification_id):
 
        """DELETE /_admin/notifications/id: Delete an existing item"""
 
        # Forms posted to this method should contain a hidden field:
 
        #    <input type="hidden" name="_method" value="DELETE" />
 
        # Or using helpers:
 
        #    h.form(url('notification', notification_id=ID),
 
        #           method='delete')
 
        # url('notification', notification_id=ID)
 

	
 
        no = Notification.get(notification_id)
 
        owner = lambda: no.notifications_to_users.user.user_id == c.rhodecode_user.user_id
 
        if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner:
 
                NotificationModel().delete(notification_id)
 
                return 'ok'
 
        try:
 
            no = Notification.get(notification_id)
 
            owner = lambda: (no.notifications_to_users.user.user_id
 
                             == c.rhodecode_user.user_id)
 
            if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner:
 
                    NotificationModel().delete(c.rhodecode_user.user_id, no)
 
                    Session.commit()
 
                    return 'ok'
 
        except Exception:
 
            Session.rollback()
 
            log.error(traceback.format_exc())
 
        return 'fail'
 

	
 
    def show(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id: Show a specific item"""
 
        # url('notification', notification_id=ID)
 
        c.user = self.rhodecode_user
 
        c.notification = Notification.get(notification_id)
 
        no = Notification.get(notification_id)
 

	
 
        owner = lambda: (no.notifications_to_users.user.user_id
 
                         == c.user.user_id)
 
        if no and (h.HasPermissionAny('hg.admin', 'repository.admin')() or owner):
 
            unotification = NotificationModel()\
 
                            .get_user_notification(c.user.user_id, no)
 

	
 
        unotification = NotificationModel()\
 
                            .get_user_notification(c.user.user_id,
 
                                                   c.notification)
 
            # if this association to user is not valid, we don't want to show
 
            # this message
 
            if unotification:
 
                if unotification.read is False:
 
                    unotification.mark_as_read()
 
                    Session.commit()
 
                c.notification = no
 

	
 
        if unotification.read is False:
 
            unotification.mark_as_read()
 
                return render('admin/notifications/show_notification.html')
 

	
 
        return render('admin/notifications/show_notification.html')
 
        return redirect(url('notifications'))
 

	
 
    def edit(self, notification_id, format='html'):
 
        """GET /_admin/notifications/id/edit: Form to edit an existing item"""
 
        # url('edit_notification', notification_id=ID)
rhodecode/controllers/changeset.py
Show inline comments
 
@@ -35,24 +35,25 @@ import rhodecode.lib.helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasRepoPermissionAnyDecorator
 
from rhodecode.lib.base import BaseRepoController, render
 
from rhodecode.lib.utils import EmptyChangeset
 
from rhodecode.lib.compat import OrderedDict
 
from rhodecode.model.db import ChangesetComment
 
from rhodecode.model.comment import ChangesetCommentsModel
 

	
 
from vcs.exceptions import RepositoryError, ChangesetError, \
 
    ChangesetDoesNotExistError
 
from vcs.nodes import FileNode
 
from vcs.utils import diffs as differ
 
from webob.exc import HTTPForbidden
 
from rhodecode.model.meta import Session
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetController(BaseRepoController):
 

	
 
    @LoginRequired()
 
    @HasRepoPermissionAnyDecorator('repository.read', 'repository.write',
 
                                   'repository.admin')
 
    def __before__(self):
 
        super(ChangesetController, self).__before__()
 
        c.affected_files_cut_off = 60
 
@@ -270,27 +271,27 @@ class ChangesetController(BaseRepoContro
 
        for x in c.changes:
 
            c.diffs += x[2]
 

	
 
        return render('changeset/raw_changeset.html')
 

	
 
    def comment(self, repo_name, revision):
 
        ChangesetCommentsModel().create(text=request.POST.get('text'),
 
                                        repo_id=c.rhodecode_db_repo.repo_id,
 
                                        user_id=c.rhodecode_user.user_id,
 
                                        revision=revision,
 
                                        f_path=request.POST.get('f_path'),
 
                                        line_no=request.POST.get('line'))
 

	
 
        Session.commit()
 
        return redirect(h.url('changeset_home', repo_name=repo_name,
 
                              revision=revision))
 

	
 
    @jsonify
 
    def delete_comment(self, comment_id):
 
        co = ChangesetComment.get(comment_id)
 
        owner = lambda : co.author.user_id == c.rhodecode_user.user_id
 
        if h.HasPermissionAny('hg.admin', 'repository.admin')() or owner:
 
            ccmodel = ChangesetCommentsModel()
 
            ccmodel.delete(comment_id=comment_id)
 
            ChangesetCommentsModel().delete(comment=co)
 
            Session.commit()
 
            return True
 
        else:
 
            raise HTTPForbidden()
 

	
rhodecode/lib/__init__.py
Show inline comments
 
@@ -15,24 +15,25 @@
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import os
 
import re
 

	
 
def __get_lem():
 
    from pygments import lexers
 
    from string import lower
 
    from collections import defaultdict
 

	
 
    d = defaultdict(lambda: [])
 

	
 
    def __clean(s):
 
        s = s.lstrip('*')
 
        s = s.lstrip('.')
 

	
 
@@ -69,37 +70,37 @@ LANGUAGES_EXTENSIONS_MAP.update(ADDITION
 
# list of readme files to search in file tree and display in summary
 
# attached weights defines the search  order lower is first
 
ALL_READMES = [
 
    ('readme', 0), ('README', 0), ('Readme', 0),
 
    ('doc/readme', 1), ('doc/README', 1), ('doc/Readme', 1),
 
    ('Docs/readme', 2), ('Docs/README', 2), ('Docs/Readme', 2),
 
    ('DOCS/readme', 2), ('DOCS/README', 2), ('DOCS/Readme', 2),
 
    ('docs/readme', 2), ('docs/README', 2), ('docs/Readme', 2),
 
]
 

	
 
# extension together with weights to search lower is first
 
RST_EXTS = [
 
    ('', 0), ('.rst', 1),('.rest', 1),
 
    ('.RST', 2) ,('.REST', 2), 
 
    ('.txt', 3), ('.TXT', 3) 
 
    ('', 0), ('.rst', 1), ('.rest', 1),
 
    ('.RST', 2) , ('.REST', 2),
 
    ('.txt', 3), ('.TXT', 3)
 
]
 

	
 
MARKDOWN_EXTS = [
 
    ('.md', 1), ('.MD', 1),
 
    ('.mkdn', 2), ('.MKDN', 2),
 
    ('.mdown', 3), ('.MDOWN', 3),
 
    ('.markdown', 4), ('.MARKDOWN', 4)
 
]
 

	
 
PLAIN_EXTS = [('.text', 2),('.TEXT', 2)]
 
PLAIN_EXTS = [('.text', 2), ('.TEXT', 2)]
 

	
 
ALL_EXTS = MARKDOWN_EXTS + RST_EXTS + PLAIN_EXTS
 

	
 

	
 
def str2bool(_str):
 
    """
 
    returs True/False value from given string, it tries to translate the
 
    string into boolean
 

	
 
    :param _str: string value to translate into boolean
 
    :rtype: boolean
 
    :returns: boolean from given string
 
@@ -214,25 +215,25 @@ def safe_unicode(str_, from_encoding='ut
 

	
 
def safe_str(unicode_, to_encoding='utf8'):
 
    """
 
    safe str function. Does few trick to turn unicode_ into string
 
     
 
    In case of UnicodeEncodeError we try to return it with encoding detected
 
    by chardet library if it fails fallback to string with errors replaced
 

	
 
    :param unicode_: unicode to encode
 
    :rtype: str
 
    :returns: str object
 
    """
 
    
 

	
 
    if not isinstance(unicode_, basestring):
 
        return str(unicode_)
 

	
 
    if isinstance(unicode_, str):
 
        return unicode_
 

	
 
    try:
 
        return unicode_.encode(to_encoding)
 
    except UnicodeEncodeError:
 
        pass
 

	
 
    try:
 
@@ -427,12 +428,23 @@ def get_current_revision(quiet=False):
 
        from vcs.utils.helpers import get_scm
 
        repopath = os.path.join(os.path.dirname(__file__), '..', '..')
 
        scm = get_scm(repopath)[0]
 
        repo = get_repo(path=repopath, alias=scm)
 
        tip = repo.get_changeset()
 
        return (tip.revision, tip.short_id)
 
    except Exception, err:
 
        if not quiet:
 
            print ("Cannot retrieve rhodecode's revision. Original error "
 
                   "was: %s" % err)
 
        return None
 

	
 
def extract_mentioned_users(s):
 
    """
 
    Returns unique usernames from given string s that have @mention
 
    
 
    :param s: string to get mentions
 
    """
 
    usrs = {}
 
    for username in re.findall(r'(?:^@|\s@)(\w+)', s):
 
        usrs[username] = username
 

	
 
    return sorted(usrs.keys())
rhodecode/lib/celerylib/tasks.py
Show inline comments
 
@@ -46,26 +46,24 @@ from rhodecode.lib.utils import add_cach
 
from rhodecode.lib.compat import json, OrderedDict
 

	
 
from rhodecode.model import init_model
 
from rhodecode.model import meta
 
from rhodecode.model.db import RhodeCodeUi, Statistics, Repository, User
 

	
 
from vcs.backends import get_repo
 

	
 
from sqlalchemy import engine_from_config
 

	
 
add_cache(config)
 

	
 

	
 

	
 
__all__ = ['whoosh_index', 'get_commits_stats',
 
           'reset_user_password', 'send_email']
 

	
 
CELERY_ON = str2bool(config['app_conf'].get('use_celery'))
 

	
 

	
 
def get_session():
 
    if CELERY_ON:
 
        engine = engine_from_config(config, 'sqlalchemy.db1.')
 
        init_model(engine)
 
    sa = meta.Session()
 
    return sa
 
@@ -92,47 +90,46 @@ def whoosh_index(repo_location, full_ind
 
def get_commits_stats(repo_name, ts_min_y, ts_max_y):
 
    try:
 
        log = get_commits_stats.get_logger()
 
    except:
 
        log = logging.getLogger(__name__)
 

	
 
    lockkey = __get_lockkey('get_commits_stats', repo_name, ts_min_y,
 
                            ts_max_y)
 
    lockkey_path = config['here']
 

	
 
    log.info('running task with lockkey %s', lockkey)
 
    try:
 
        sa = get_session()
 
        lock = l = DaemonLock(file_=jn(lockkey_path, lockkey))
 

	
 
        #for js data compatibilty cleans the key for person from '
 
        akc = lambda k: person(k).replace('"', "")
 

	
 
        co_day_auth_aggr = {}
 
        commits_by_day_aggregate = {}
 
        repos_path = get_repos_path()
 
        repo = get_repo(safe_str(os.path.join(repos_path, repo_name)))
 
        repo_size = len(repo.revisions)
 
        #return if repo have no revisions
 
        if repo_size < 1:
 
            lock.release()
 
            return True
 

	
 
        skip_date_limit = True
 
        parse_limit = int(config['app_conf'].get('commit_parse_limit'))
 
        last_rev = 0
 
        last_cs = None
 
        timegetter = itemgetter('time')
 

	
 
        sa = get_session()
 

	
 
        dbrepo = sa.query(Repository)\
 
            .filter(Repository.repo_name == repo_name).scalar()
 
        cur_stats = sa.query(Statistics)\
 
            .filter(Statistics.repository == dbrepo).scalar()
 

	
 
        if cur_stats is not None:
 
            last_rev = cur_stats.stat_on_revision
 

	
 
        if last_rev == repo.get_changeset().revision and repo_size > 1:
 
            #pass silently without any work if we're not on first revision or
 
            #current state of parsing revision(from db marker) is the
 
            #last revision
rhodecode/model/__init__.py
Show inline comments
 
@@ -62,13 +62,31 @@ def init_model(engine):
 

	
 
class BaseModel(object):
 
    """Base Model for all RhodeCode models, it adds sql alchemy session
 
    into instance of model
 

	
 
    :param sa: If passed it reuses this session instead of creating a new one
 
    """
 

	
 
    def __init__(self, sa=None):
 
        if sa is not None:
 
            self.sa = sa
 
        else:
 
            self.sa = meta.Session
 
            self.sa = meta.Session()
 

	
 
    def __get_instance(self, cls, instance):
 
        """
 
        Get's instance of given cls using some simple lookup mechanism
 
        
 
        :param cls: class to fetch
 
        :param instance: int or Instance
 
        """
 

	
 
        if isinstance(instance, cls):
 
            return instance
 
        elif isinstance(instance, int) or str(instance).isdigit():
 
            return cls.get(instance)
 
        else:
 
            if instance:
 
                raise Exception('given object must be int or Instance'
 
                                ' of %s got %s' % (type(cls),
 
                                                   type(instance)))
rhodecode/model/comment.py
Show inline comments
 
@@ -14,50 +14,51 @@
 
# it under the terms of the GNU General Public License as published by
 
# the Free Software Foundation, either version 3 of the License, or
 
# (at your option) any later version.
 
#
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
#
 
# You should have received a copy of the GNU General Public License
 
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
 

	
 
import re
 
import logging
 
import traceback
 

	
 
from pylons.i18n.translation import _
 
from sqlalchemy.util.compat import defaultdict
 

	
 
from rhodecode.lib import extract_mentioned_users
 
from rhodecode.lib import helpers as h
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import ChangesetComment, User, Repository, Notification
 
from rhodecode.model.notification import NotificationModel
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class ChangesetCommentsModel(BaseModel):
 

	
 
    def __get_changeset_comment(self, changeset_comment):
 
        return self.__get_instance(ChangesetComment, changeset_comment)
 

	
 
    def _extract_mentions(self, s):
 
        usrs = []
 
        for username in re.findall(r'(?:^@|\s@)(\w+)', s):
 
        user_objects = []
 
        for username in extract_mentioned_users(s):
 
            user_obj = User.get_by_username(username, case_insensitive=True)
 
            if user_obj:
 
                usrs.append(user_obj)
 

	
 
        return usrs
 
                user_objects.append(user_obj)
 
        return user_objects
 

	
 
    def create(self, text, repo_id, user_id, revision, f_path=None,
 
               line_no=None):
 
        """
 
        Creates new comment for changeset
 
        
 
        :param text:
 
        :param repo_id:
 
        :param user_id:
 
        :param revision:
 
        :param f_path:
 
        :param line_no:
 
@@ -72,48 +73,48 @@ class ChangesetCommentsModel(BaseModel):
 
            comment.text = text
 
            comment.f_path = f_path
 
            comment.line_no = line_no
 

	
 
            self.sa.add(comment)
 
            self.sa.flush()
 

	
 
            # make notification
 
            line = ''
 
            if line_no:
 
                line = _('on line %s') % line_no
 
            subj = h.link_to('Re commit: %(commit_desc)s %(line)s' % \
 
                                    {'commit_desc':desc,'line':line},
 
                                    {'commit_desc':desc, 'line':line},
 
                             h.url('changeset_home', repo_name=repo.repo_name,
 
                                   revision = revision,
 
                                   anchor = 'comment-%s' % comment.comment_id
 
                                   revision=revision,
 
                                   anchor='comment-%s' % comment.comment_id
 
                                   )
 
                             )
 
            body = text
 
            recipients = ChangesetComment.get_users(revision=revision)
 
            recipients += self._extract_mentions(body)
 
            NotificationModel().create(created_by=user_id, subject=subj,
 
                                   body = body, recipients = recipients,
 
                                   type_ = Notification.TYPE_CHANGESET_COMMENT)
 
                                   body=body, recipients=recipients,
 
                                   type_=Notification.TYPE_CHANGESET_COMMENT)
 

	
 
            return comment
 

	
 
    def delete(self, comment_id):
 
    def delete(self, comment):
 
        """
 
        Deletes given comment
 
        
 
        :param comment_id:
 
        """
 
        comment = ChangesetComment.get(comment_id)
 
        comment = self.__get_changeset_comment(comment)
 
        self.sa.delete(comment)
 
        self.sa.commit()
 

	
 
        return comment
 

	
 

	
 
    def get_comments(self, repo_id, revision):
 
        return ChangesetComment.query()\
 
                .filter(ChangesetComment.repo_id == repo_id)\
 
                .filter(ChangesetComment.revision == revision)\
 
                .filter(ChangesetComment.line_no == None)\
 
                .filter(ChangesetComment.f_path == None).all()
 

	
 
    def get_inline_comments(self, repo_id, revision):
 
        comments = self.sa.query(ChangesetComment)\
rhodecode/model/db.py
Show inline comments
 
@@ -39,25 +39,24 @@ from vcs import get_backend
 
from vcs.utils.helpers import get_scm
 
from vcs.exceptions import VCSError
 
from vcs.utils.lazy import LazyProperty
 

	
 
from rhodecode.lib import str2bool, safe_str, get_changeset_safe, \
 
    generate_api_key, safe_unicode
 
from rhodecode.lib.exceptions import UsersGroupsAssignedException
 
from rhodecode.lib.compat import json
 
from rhodecode.lib.caching_query import FromCache
 

	
 
from rhodecode.model.meta import Base, Session
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 
#==============================================================================
 
# BASE CLASSES
 
#==============================================================================
 

	
 
class ModelSerializer(json.JSONEncoder):
 
    """
 
    Simple Serializer for JSON,
 

	
 
    usage::
 

	
 
@@ -113,40 +112,39 @@ class BaseModel(object):
 
            l.append((k, getattr(self, k),))
 
        return l
 

	
 
    def populate_obj(self, populate_dict):
 
        """populate model with data from given populate_dict"""
 

	
 
        for k in self._get_keys():
 
            if k in populate_dict:
 
                setattr(self, k, populate_dict[k])
 

	
 
    @classmethod
 
    def query(cls):
 
        return Session.query(cls)
 
        return Session().query(cls)
 

	
 
    @classmethod
 
    def get(cls, id_):
 
        if id_:
 
            return cls.query().get(id_)
 

	
 
    @classmethod
 
    def getAll(cls):
 
        return cls.query().all()
 

	
 
    @classmethod
 
    def delete(cls, id_):
 
        obj = cls.query().get(id_)
 
        Session.delete(obj)
 
        Session.commit()
 
        Session().delete(obj)
 

	
 

	
 
class RhodeCodeSetting(Base, BaseModel):
 
    __tablename__ = 'rhodecode_settings'
 
    __table_args__ = (UniqueConstraint('app_settings_name'), {'extend_existing':True})
 
    app_settings_id = Column("app_settings_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    app_settings_name = Column("app_settings_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    _app_settings_value = Column("app_settings_value", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    def __init__(self, k='', v=''):
 
        self.app_settings_name = k
 
        self.app_settings_value = v
 
@@ -248,26 +246,26 @@ class RhodeCodeUi(Base, BaseModel):
 
                                    cls.HOOK_PUSH, cls.HOOK_PULL]))
 
        q = q.filter(cls.ui_section == 'hooks')
 
        return q.all()
 

	
 
    @classmethod
 
    def create_or_update_hook(cls, key, val):
 
        new_ui = cls.get_by_key(key).scalar() or cls()
 
        new_ui.ui_section = 'hooks'
 
        new_ui.ui_active = True
 
        new_ui.ui_key = key
 
        new_ui.ui_value = val
 

	
 
        Session.add(new_ui)
 
        Session.commit()
 
        Session().add(new_ui)
 
        Session().commit()
 

	
 

	
 
class User(Base, BaseModel):
 
    __tablename__ = 'users'
 
    __table_args__ = (UniqueConstraint('username'), UniqueConstraint('email'), {'extend_existing':True})
 
    user_id = Column("user_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    username = Column("username", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    password = Column("password", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    active = Column("active", Boolean(), nullable=True, unique=None, default=None)
 
    admin = Column("admin", Boolean(), nullable=True, unique=None, default=False)
 
    name = Column("name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    lastname = Column("lastname", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
@@ -276,27 +274,25 @@ class User(Base, BaseModel):
 
    ldap_dn = Column("ldap_dn", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    api_key = Column("api_key", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 

	
 
    user_log = relationship('UserLog', cascade='all')
 
    user_perms = relationship('UserToPerm', primaryjoin="User.user_id==UserToPerm.user_id", cascade='all')
 

	
 
    repositories = relationship('Repository')
 
    user_followers = relationship('UserFollowing', primaryjoin='UserFollowing.follows_user_id==User.user_id', cascade='all')
 
    repo_to_perm = relationship('UserRepoToPerm', primaryjoin='UserRepoToPerm.user_id==User.user_id', cascade='all')
 

	
 
    group_member = relationship('UsersGroupMember', cascade='all')
 

	
 
    notifications = relationship('Notification',
 
                            secondary='user_to_notification',
 
                            order_by=lambda :Notification.created_on.desc())
 
    notifications = relationship('UserNotification')
 

	
 
    @property
 
    def full_contact(self):
 
        return '%s %s <%s>' % (self.name, self.lastname, self.email)
 

	
 
    @property
 
    def short_contact(self):
 
        return '%s %s' % (self.name, self.lastname)
 

	
 
    @property
 
    def is_admin(self):
 
        return self.admin
 
@@ -322,26 +318,26 @@ class User(Base, BaseModel):
 
    def get_by_api_key(cls, api_key, cache=False):
 
        q = cls.query().filter(cls.api_key == api_key)
 

	
 
        if cache:
 
            q = q.options(FromCache("sql_cache_short",
 
                                    "get_api_key_%s" % api_key))
 
        return q.scalar()
 

	
 
    def update_lastlogin(self):
 
        """Update user lastlogin"""
 

	
 
        self.last_login = datetime.datetime.now()
 
        Session.add(self)
 
        Session.commit()
 
        Session().add(self)
 
        Session().commit()
 
        log.debug('updated user %s lastlogin', self.username)
 

	
 

	
 
class UserLog(Base, BaseModel):
 
    __tablename__ = 'user_logs'
 
    __table_args__ = {'extend_existing':True}
 
    user_log_id = Column("user_log_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 
    repository_name = Column("repository_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    user_ip = Column("user_ip", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
    action = Column("action", UnicodeText(length=1200000, convert_unicode=False, assert_unicode=None), nullable=True, unique=None, default=None)
 
@@ -388,101 +384,101 @@ class UsersGroup(Base, BaseModel):
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                    "get_users_group_%s" % users_group_id))
 
        return users_group.get(users_group_id)
 

	
 
    @classmethod
 
    def create(cls, form_data):
 
        try:
 
            new_users_group = cls()
 
            for k, v in form_data.items():
 
                setattr(new_users_group, k, v)
 

	
 
            Session.add(new_users_group)
 
            Session.commit()
 
            Session().add(new_users_group)
 
            Session().commit()
 
            return new_users_group
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 
            raise
 

	
 
    @classmethod
 
    def update(cls, users_group_id, form_data):
 

	
 
        try:
 
            users_group = cls.get(users_group_id, cache=False)
 

	
 
            for k, v in form_data.items():
 
                if k == 'users_group_members':
 
                    users_group.members = []
 
                    Session.flush()
 
                    Session().flush()
 
                    members_list = []
 
                    if v:
 
                        v = [v] if isinstance(v, basestring) else v
 
                        for u_id in set(v):
 
                            member = UsersGroupMember(users_group_id, u_id)
 
                            members_list.append(member)
 
                    setattr(users_group, 'members', members_list)
 
                setattr(users_group, k, v)
 

	
 
            Session.add(users_group)
 
            Session.commit()
 
            Session().add(users_group)
 
            Session().commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 
            raise
 

	
 
    @classmethod
 
    def delete(cls, users_group_id):
 
        try:
 

	
 
            # check if this group is not assigned to repo
 
            assigned_groups = UsersGroupRepoToPerm.query()\
 
                .filter(UsersGroupRepoToPerm.users_group_id ==
 
                        users_group_id).all()
 

	
 
            if assigned_groups:
 
                raise UsersGroupsAssignedException('RepoGroup assigned to %s' %
 
                                                   assigned_groups)
 

	
 
            users_group = cls.get(users_group_id, cache=False)
 
            Session.delete(users_group)
 
            Session.commit()
 
            Session().delete(users_group)
 
            Session().commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 
            raise
 

	
 
class UsersGroupMember(Base, BaseModel):
 
    __tablename__ = 'users_groups_members'
 
    __table_args__ = {'extend_existing':True}
 

	
 
    users_group_member_id = Column("users_group_member_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User', lazy='joined')
 
    users_group = relationship('UsersGroup')
 

	
 
    def __init__(self, gr_id='', u_id=''):
 
        self.users_group_id = gr_id
 
        self.user_id = u_id
 

	
 
    @staticmethod
 
    def add_user_to_group(group, user):
 
        ugm = UsersGroupMember()
 
        ugm.users_group = group
 
        ugm.user = user
 
        Session.add(ugm)
 
        Session.commit()
 
        Session().add(ugm)
 
        Session().commit()
 
        return ugm
 

	
 
class Repository(Base, BaseModel):
 
    __tablename__ = 'repositories'
 
    __table_args__ = (UniqueConstraint('repo_name'), {'extend_existing':True},)
 

	
 
    repo_id = Column("repo_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    repo_name = Column("repo_name", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=True, default=None)
 
    clone_uri = Column("clone_uri", String(length=255, convert_unicode=False, assert_unicode=None), nullable=True, unique=False, default=None)
 
    repo_type = Column("repo_type", String(length=255, convert_unicode=False, assert_unicode=None), nullable=False, unique=False, default='hg')
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=False, default=None)
 
    private = Column("private", Boolean(), nullable=True, unique=None, default=None)
 
@@ -507,42 +503,42 @@ class Repository(Base, BaseModel):
 
    logs = relationship('UserLog', cascade='all')
 

	
 
    def __repr__(self):
 
        return "<%s('%s:%s')>" % (self.__class__.__name__,
 
                                  self.repo_id, self.repo_name)
 

	
 
    @classmethod
 
    def url_sep(cls):
 
        return '/'
 

	
 
    @classmethod
 
    def get_by_repo_name(cls, repo_name):
 
        q = Session.query(cls).filter(cls.repo_name == repo_name)
 
        q = Session().query(cls).filter(cls.repo_name == repo_name)
 
        q = q.options(joinedload(Repository.fork))\
 
                .options(joinedload(Repository.user))\
 
                .options(joinedload(Repository.group))
 
        return q.one()
 

	
 
    @classmethod
 
    def get_repo_forks(cls, repo_id):
 
        return cls.query().filter(Repository.fork_id == repo_id)
 

	
 
    @classmethod
 
    def base_path(cls):
 
        """
 
        Returns base path when all repos are stored
 

	
 
        :param cls:
 
        """
 
        q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
        q = Session().query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
                                              cls.url_sep())
 
        q.options(FromCache("sql_cache_short", "repository_repo_path"))
 
        return q.one().ui_value
 

	
 
    @property
 
    def just_name(self):
 
        return self.repo_name.split(Repository.url_sep())[-1]
 

	
 
    @property
 
    def groups_with_parents(self):
 
        groups = []
 
        if self.group is None:
 
@@ -560,25 +556,25 @@ class Repository(Base, BaseModel):
 
        return groups
 

	
 
    @property
 
    def groups_and_repo(self):
 
        return self.groups_with_parents, self.just_name
 

	
 
    @LazyProperty
 
    def repo_path(self):
 
        """
 
        Returns base full path for that repository means where it actually
 
        exists on a filesystem
 
        """
 
        q = Session.query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
        q = Session().query(RhodeCodeUi).filter(RhodeCodeUi.ui_key ==
 
                                              Repository.url_sep())
 
        q.options(FromCache("sql_cache_short", "repository_repo_path"))
 
        return q.one().ui_value
 

	
 
    @property
 
    def repo_full_path(self):
 
        p = [self.repo_path]
 
        # we need to split the name by / since this is how we store the
 
        # names in the database, but that eventually needs to be converted
 
        # into a valid system path
 
        p += self.repo_name.split(Repository.url_sep())
 
        return os.path.join(*p)
 
@@ -877,41 +873,42 @@ class UserToPerm(Base, BaseModel):
 
        return cls.query().filter(cls.user_id == user_id)\
 
            .filter(cls.permission == perm).scalar() is not None
 

	
 
    @classmethod
 
    def grant_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        new = cls()
 
        new.user_id = user_id
 
        new.permission = perm
 
        try:
 
            Session.add(new)
 
            Session.commit()
 
            Session().add(new)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 

	
 
    @classmethod
 
    def revoke_perm(cls, user_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            cls.query().filter(cls.user_id == user_id)\
 
                .filter(cls.permission == perm).delete()
 
            Session.commit()
 
            obj = cls.query().filter(cls.user_id == user_id)\
 
                    .filter(cls.permission == perm).one()
 
            Session().delete(obj)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 
class UsersGroupRepoToPerm(Base, BaseModel):
 
    __tablename__ = 'users_group_repo_to_perm'
 
    __table_args__ = (UniqueConstraint('repository_id', 'users_group_id', 'permission_id'), {'extend_existing':True})
 
    users_group_to_perm_id = Column("users_group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    users_group_id = Column("users_group_id", Integer(), ForeignKey('users_groups.users_group_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    repository_id = Column("repository_id", Integer(), ForeignKey('repositories.repo_id'), nullable=False, unique=None, default=None)
 

	
 
    users_group = relationship('UsersGroup')
 
    permission = relationship('Permission')
 
    repository = relationship('Repository')
 
@@ -939,41 +936,42 @@ class UsersGroupToPerm(Base, BaseModel):
 
                                         .filter(cls.permission == perm)\
 
                                         .scalar() is not None
 

	
 
    @classmethod
 
    def grant_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        new = cls()
 
        new.users_group_id = users_group_id
 
        new.permission = perm
 
        try:
 
            Session.add(new)
 
            Session.commit()
 
            Session().add(new)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 

	
 
    @classmethod
 
    def revoke_perm(cls, users_group_id, perm):
 
        if not isinstance(perm, Permission):
 
            raise Exception('perm needs to be an instance of Permission class')
 

	
 
        try:
 
            cls.query().filter(cls.users_group_id == users_group_id)\
 
                .filter(cls.permission == perm).delete()
 
            Session.commit()
 
            obj = cls.query().filter(cls.users_group_id == users_group_id)\
 
                .filter(cls.permission == perm).one()
 
            Session().delete(obj)
 
            Session().commit()
 
        except:
 
            Session.rollback()
 
            Session().rollback()
 

	
 

	
 
class UserRepoGroupToPerm(Base, BaseModel):
 
    __tablename__ = 'group_to_perm'
 
    __table_args__ = (UniqueConstraint('group_id', 'permission_id'), {'extend_existing':True})
 

	
 
    group_to_perm_id = Column("group_to_perm_id", Integer(), nullable=False, unique=True, default=None, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    permission_id = Column("permission_id", Integer(), ForeignKey('permissions.permission_id'), nullable=False, unique=None, default=None)
 
    group_id = Column("group_id", Integer(), ForeignKey('groups.group_id'), nullable=False, unique=None, default=None)
 

	
 
    user = relationship('User')
 
@@ -1068,42 +1066,42 @@ class CacheInvalidation(Base, BaseModel)
 
        """
 

	
 
        log.debug('marking %s for invalidation' % key)
 
        inv_obj = Session().query(cls)\
 
            .filter(cls.cache_key == key).scalar()
 
        if inv_obj:
 
            inv_obj.cache_active = False
 
        else:
 
            log.debug('cache key not found in invalidation db -> creating one')
 
            inv_obj = CacheInvalidation(key)
 

	
 
        try:
 
            Session.add(inv_obj)
 
            Session.commit()
 
            Session().add(inv_obj)
 
            Session().commit()
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            Session.rollback()
 
            Session().rollback()
 

	
 
    @classmethod
 
    def set_valid(cls, key):
 
        """
 
        Mark this cache key as active and currently cached
 
        
 
        :param key:
 
        """
 
        inv_obj = Session().query(CacheInvalidation)\
 
        inv_obj = CacheInvalidation.query()\
 
            .filter(CacheInvalidation.cache_key == key).scalar()
 
        inv_obj.cache_active = True
 
        Session.add(inv_obj)
 
        Session.commit()
 
        Session().add(inv_obj)
 
        Session().commit()
 

	
 

	
 
class ChangesetComment(Base, BaseModel):
 
    __tablename__ = 'changeset_comments'
 
    __table_args__ = ({'extend_existing':True},)
 
    comment_id = Column('comment_id', Integer(), nullable=False, primary_key=True)
 
    repo_id = Column('repo_id', Integer(), ForeignKey('repositories.repo_id'), nullable=False)
 
    revision = Column('revision', String(40), nullable=False)
 
    line_no = Column('line_no', Unicode(10), nullable=True)
 
    f_path = Column('f_path', Unicode(1000), nullable=True)
 
    user_id = Column('user_id', Integer(), ForeignKey('users.user_id'), nullable=False)
 
    text = Column('text', Unicode(25000), nullable=False)
 
@@ -1113,88 +1111,89 @@ class ChangesetComment(Base, BaseModel):
 
    repo = relationship('Repository')
 

	
 

	
 
    @classmethod
 
    def get_users(cls, revision):
 
        """
 
        Returns user associated with this changesetComment. ie those
 
        who actually commented
 
        
 
        :param cls:
 
        :param revision:
 
        """
 
        return Session.query(User)\
 
        return Session().query(User)\
 
                .filter(cls.revision == revision)\
 
                .join(ChangesetComment.author).all()
 

	
 

	
 
class Notification(Base, BaseModel):
 
    __tablename__ = 'notifications'
 
    __table_args__ = ({'extend_existing':True})
 

	
 
    TYPE_CHANGESET_COMMENT = u'cs_comment'
 
    TYPE_MESSAGE = u'message'
 
    TYPE_MENTION = u'mention'
 

	
 
    notification_id = Column('notification_id', Integer(), nullable=False, primary_key=True)
 
    subject = Column('subject', Unicode(512), nullable=True)
 
    body = Column('body', Unicode(50000), nullable=True)
 
    created_by = Column("created_by", Integer(), ForeignKey('users.user_id'), nullable=True)
 
    created_on = Column('created_on', DateTime(timezone=False), nullable=False, default=datetime.datetime.now)
 
    type_ = Column('type', Unicode(256))
 

	
 
    created_by_user = relationship('User')
 
    notifications_to_users = relationship('UserNotification',
 
        primaryjoin='Notification.notification_id==UserNotification.notification_id',
 
        lazy='joined',
 
        cascade = "all, delete, delete-orphan")
 
        cascade="all, delete, delete-orphan")
 

	
 
    @property
 
    def recipients(self):
 
        return [x.user for x in UserNotification.query()\
 
                .filter(UserNotification.notification == self).all()]
 

	
 
    @classmethod
 
    def create(cls, created_by, subject, body, recipients, type_=None):
 
        if type_ is None:
 
            type_ = Notification.TYPE_MESSAGE
 

	
 
        notification = cls()
 
        notification.created_by_user = created_by
 
        notification.subject = subject
 
        notification.body = body
 
        notification.type_ = type_
 
        Session.add(notification)
 

	
 
        for u in recipients:
 
            u.notifications.append(notification)
 
            assoc = UserNotification()
 
            assoc.notification = notification
 
            u.notifications.append(assoc)
 
        Session().add(notification)
 
        return notification
 

	
 
    @property
 
    def description(self):
 
        from rhodecode.model.notification import NotificationModel
 
        return NotificationModel().make_description(self)
 

	
 
class UserNotification(Base, BaseModel):
 
    __tablename__ = 'user_to_notification'
 
    __table_args__ = (UniqueConstraint('user_id', 'notification_id'),
 
                      {'extend_existing':True})
 
    user_to_notification_id = Column("user_to_notification_id", Integer(), nullable=False, unique=True, primary_key=True)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), nullable=False, unique=None, default=None)
 
    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), nullable=False)
 
    user_id = Column("user_id", Integer(), ForeignKey('users.user_id'), primary_key=True)
 
    notification_id = Column("notification_id", Integer(), ForeignKey('notifications.notification_id'), primary_key=True)
 
    read = Column('read', Boolean, default=False)
 
    sent_on = Column('sent_on', DateTime(timezone=False), nullable=True, unique=None)
 

	
 
    user = relationship('User', single_parent=True, lazy="joined")
 
    notification = relationship('Notification', single_parent=True,)
 
    user = relationship('User', lazy="joined")
 
    notification = relationship('Notification', lazy="joined", cascade='all')
 

	
 
    def mark_as_read(self):
 
        self.read = True
 
        Session.add(self)
 
        Session.commit()
 
        Session().add(self)
 

	
 
class DbMigrateVersion(Base, BaseModel):
 
    __tablename__ = 'db_migrate_version'
 
    __table_args__ = {'extend_existing':True}
 
    repository_id = Column('repository_id', String(250), primary_key=True)
 
    repository_path = Column('repository_path', Text)
 
    version = Column('version', Integer)
 

	
rhodecode/model/notification.py
Show inline comments
 
@@ -79,48 +79,53 @@ class NotificationModel(BaseModel):
 
            raise Exception('recipients must be a list of iterable')
 

	
 
        created_by_obj = self.__get_user(created_by)
 

	
 
        recipients_objs = []
 
        for u in recipients:
 
            recipients_objs.append(self.__get_user(u))
 
        recipients_objs = set(recipients_objs)
 
        return Notification.create(created_by=created_by_obj, subject=subject,
 
                            body=body, recipients=recipients_objs,
 
                            type_=type_)
 

	
 
    def delete(self, notification_id):
 
        # we don't want to remove actuall notification just the assignment
 
    def delete(self, user, notification):
 
        # we don't want to remove actual notification just the assignment
 
        try:
 
            notification_id = int(notification_id)
 
            no = self.__get_notification(notification_id)
 
            if no:
 
                UserNotification.delete(no.notifications_to_users.user_to_notification_id)
 
            notification = self.__get_notification(notification)
 
            user = self.__get_user(user)
 
            if notification and user:
 
                obj = UserNotification.query().filter(UserNotification.user == user)\
 
                    .filter(UserNotification.notification == notification).one()
 
                self.sa.delete(obj)
 
                return True
 
        except Exception:
 
            log.error(traceback.format_exc())
 
            raise
 

	
 
    def get_for_user(self, user_id):
 
        return User.get(user_id).notifications
 
    def get_for_user(self, user):
 
        user = self.__get_user(user)
 
        return user.notifications
 

	
 
    def get_unread_cnt_for_user(self, user_id):
 
    def get_unread_cnt_for_user(self, user):
 
        user = self.__get_user(user)
 
        return UserNotification.query()\
 
                .filter(UserNotification.read == False)\
 
                .filter(UserNotification.user_id == user_id).count()
 
                .filter(UserNotification.user == user).count()
 

	
 
    def get_unread_for_user(self, user_id):
 
    def get_unread_for_user(self, user):
 
        user = self.__get_user(user)
 
        return [x.notification for x in UserNotification.query()\
 
                .filter(UserNotification.read == False)\
 
                .filter(UserNotification.user_id == user_id).all()]
 
                .filter(UserNotification.user == user).all()]
 

	
 
    def get_user_notification(self, user, notification):
 
        user = self.__get_user(user)
 
        notification = self.__get_notification(notification)
 

	
 
        return UserNotification.query()\
 
            .filter(UserNotification.notification == notification)\
 
            .filter(UserNotification.user == user).scalar()
 

	
 
    def make_description(self, notification):
 
        """
 
        Creates a human readable description based on properties
rhodecode/model/repo.py
Show inline comments
 
@@ -291,52 +291,55 @@ class RepoModel(BaseModel):
 
    def delete(self, repo):
 
        try:
 
            self.sa.delete(repo)
 
            self.__delete_repo(repo)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_perm_user(self, form_data, repo_name):
 
        try:
 
            self.sa.query(UserRepoToPerm)\
 
            obj = self.sa.query(UserRepoToPerm)\
 
                .filter(UserRepoToPerm.repository \
 
                        == self.get_by_repo_name(repo_name))\
 
                .filter(UserRepoToPerm.user_id == form_data['user_id']).delete()
 
                .filter(UserRepoToPerm.user_id == form_data['user_id']).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_perm_users_group(self, form_data, repo_name):
 
        try:
 
            self.sa.query(UsersGroupRepoToPerm)\
 
            obj = self.sa.query(UsersGroupRepoToPerm)\
 
                .filter(UsersGroupRepoToPerm.repository \
 
                        == self.get_by_repo_name(repo_name))\
 
                .filter(UsersGroupRepoToPerm.users_group_id \
 
                        == form_data['users_group_id']).delete()
 
 == form_data['users_group_id']).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def delete_stats(self, repo_name):
 
        try:
 
            self.sa.query(Statistics)\
 
                .filter(Statistics.repository == \
 
                        self.get_by_repo_name(repo_name)).delete()
 
            obj = self.sa.query(Statistics)\
 
                    .filter(Statistics.repository == \
 
                        self.get_by_repo_name(repo_name)).one()
 
            self.sa.delete(obj)
 
            self.sa.commit()
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 
    def __create_repo(self, repo_name, alias, new_parent_id, clone_uri=False):
 
        """
 
        makes repository on filesystem. It's group aware means it'll create
 
        a repository within a group, and alter the paths accordingly of
 
        group location
 

	
rhodecode/model/user.py
Show inline comments
 
@@ -344,25 +344,25 @@ class UserModel(BaseModel):
 
        works for permissions given for repositories, and for permissions that
 
        are granted to groups
 

	
 
        :param user: user instance to fill his perms
 
        """
 

	
 
        user.permissions['repositories'] = {}
 
        user.permissions['global'] = set()
 

	
 
        #======================================================================
 
        # fetch default permissions
 
        #======================================================================
 
        default_user = self.get_by_username('default')
 
        default_user = User.get_by_username('default')
 

	
 
        default_perms = self.sa.query(UserRepoToPerm, Repository, Permission)\
 
            .join((Repository, UserRepoToPerm.repository_id ==
 
                   Repository.repo_id))\
 
            .join((Permission, UserRepoToPerm.permission_id ==
 
                   Permission.permission_id))\
 
            .filter(UserRepoToPerm.user == default_user).all()
 

	
 
        if user.is_admin:
 
            #==================================================================
 
            # #admin have all default rights set to admin
 
            #==================================================================
rhodecode/model/users_group.py
Show inline comments
 
@@ -26,56 +26,59 @@
 
import logging
 
import traceback
 

	
 
from rhodecode.lib.caching_query import FromCache
 

	
 
from rhodecode.model import BaseModel
 
from rhodecode.model.db import UsersGroupMember, UsersGroup
 

	
 
log = logging.getLogger(__name__)
 

	
 
class UsersGroupModel(BaseModel):
 

	
 
    def __get_users_group(self, users_group):
 
        return self.__get_instance(UsersGroup, users_group)
 

	
 
    def get(self, users_group_id, cache = False):
 
        users_group = UsersGroup.query()
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                          "get_users_group_%s" % users_group_id))
 
        return users_group.get(users_group_id)
 
        return UsersGroup.get(users_group_id)
 

	
 
    def get_by_name(self, name, cache = False, case_insensitive = False):
 
        users_group = UsersGroup.query()
 
        if case_insensitive:
 
            users_group = users_group.filter(UsersGroup.users_group_name.ilike(name))
 
        else:
 
            users_group = users_group.filter(UsersGroup.users_group_name == name)
 
        if cache:
 
            users_group = users_group.options(FromCache("sql_cache_short",
 
                                          "get_users_group_%s" % name))
 
        return users_group.scalar()
 
        return UsersGroup.get_by_group_name(name, cache, case_insensitive)
 

	
 
    def create(self, form_data):
 
        try:
 
            new_users_group = UsersGroup()
 
            for k, v in form_data.items():
 
                setattr(new_users_group, k, v)
 

	
 
            self.sa.add(new_users_group)
 
            self.sa.commit()
 
            return new_users_group
 
        except:
 
            log.error(traceback.format_exc())
 
            self.sa.rollback()
 
            raise
 

	
 

	
 
    def create_(self, name, active=True):
 
        new = UsersGroup()
 
        new.users_group_name = name
 
        new.users_group_active = active
 
        self.sa.add(new)
 
        return new
 

	
 
    def delete(self, users_group):
 
        obj = self.__get_users_group(users_group)
 
        self.sa.delete(obj)
 

	
 
    def add_user_to_group(self, users_group, user):
 
        for m in users_group.members:
 
            u = m.user
 
            if u.user_id == user.user_id:
 
                return m
 

	
 
        try:
 
            users_group_member = UsersGroupMember()
 
            users_group_member.user = user
 
            users_group_member.users_group = users_group
 

	
 
            users_group.members.append(users_group_member)
rhodecode/templates/admin/notifications/notifications.html
Show inline comments
 
@@ -21,37 +21,37 @@
 
        <ul class="links">
 
            <li>
 
              <span style="text-transform: uppercase;"><a href="#">${_('Compose message')}</a></span>
 
            </li>          
 
        </ul>            
 
    </div>
 
    % if c.notifications:
 
    <%
 
    unread = lambda n:{False:'unread'}.get(n)
 
    %>
 
    <div class="table">
 
      %for notification in c.notifications:
 
        <div id="notification_${notification.notification_id}">
 
        <div id="notification_${notification.notification.notification_id}">
 
          <div class="notification-header">
 
            <div class="gravatar">
 
                <img alt="gravatar" src="${h.gravatar_url(h.email(notification.created_by_user.email),24)}"/>
 
                <img alt="gravatar" src="${h.gravatar_url(h.email(notification.notification.created_by_user.email),24)}"/>
 
            </div>
 
            <div class="desc">
 
            <a href="${url('notification', notification_id=notification.notification_id)}">${notification.description}</a>
 
            <div class="desc ${unread(notification.read)}">
 
            <a href="${url('notification', notification_id=notification.notification.notification_id)}">${notification.notification.description}</a>
 
            </div>
 
            <div class="delete-notifications">
 
              <span id="${notification.notification_id}" class="delete-notification delete_icon action"></span>
 
              <span id="${notification.notification.notification_id}" class="delete-notification delete_icon action"></span>
 
            </div>
 
          </div>
 
          <div class="notification-subject">${h.urlify_text(notification.subject)}</div>
 
          <div class="notification-subject">${h.urlify_text(notification.notification.subject)}</div>
 
        </div>
 
      %endfor
 
    </div>
 
    %else:
 
        <div class="table">${_('No notifications here yet')}</div>
 
    %endif
 
</div>
 
<script type="text/javascript">
 
var url = "${url('notification', notification_id='__NOTIFICATION_ID__')}";
 
   YUE.on(YUQ('.delete-notification'),'click',function(e){
 
	   var notification_id = e.currentTarget.id;
 
	   deleteNotification(url,notification_id)
rhodecode/tests/__init__.py
Show inline comments
 
@@ -55,25 +55,25 @@ NEW_GIT_REPO = 'vcs_test_git_new'
 

	
 
HG_FORK = 'vcs_test_hg_fork'
 
GIT_FORK = 'vcs_test_git_fork'
 

	
 
class TestController(TestCase):
 

	
 
    def __init__(self, *args, **kwargs):
 
        wsgiapp = pylons.test.pylonsapp
 
        config = wsgiapp.config
 

	
 
        self.app = TestApp(wsgiapp)
 
        url._push_object(URLGenerator(config['routes.map'], environ))
 
        self.sa = meta.Session
 
        self.Session = meta.Session
 
        self.index_location = config['app_conf']['index_dir']
 
        TestCase.__init__(self, *args, **kwargs)
 

	
 
    def log_user(self, username=TEST_USER_ADMIN_LOGIN,
 
                 password=TEST_USER_ADMIN_PASS):
 
        self._logged_username = username
 
        response = self.app.post(url(controller='login', action='index'),
 
                                 {'username':username,
 
                                  'password':password})
 

	
 
        if 'invalid user name' in response.body:
 
            self.fail('could not login using %s %s' % (username, password))
rhodecode/tests/functional/test_admin_ldap_settings.py
Show inline comments
 
@@ -33,24 +33,25 @@ class TestLdapSettingsController(TestCon
 
                    'ldap_tls_reqcert' : 'NEVER',
 
                    'ldap_dn_user':'test_user',
 
                    'ldap_dn_pass':'test_pass',
 
                    'ldap_base_dn':'test_base_dn',
 
                    'ldap_filter':'test_filter',
 
                    'ldap_search_scope':'BASE',
 
                    'ldap_attr_login':'test_attr_login',
 
                    'ldap_attr_firstname':'ima',
 
                    'ldap_attr_lastname':'tester',
 
                    'ldap_attr_email':'test@example.com' })
 

	
 
        new_settings = RhodeCodeSetting.get_ldap_settings()
 
        print new_settings
 
        self.assertEqual(new_settings['ldap_host'], u'dc.example.com',
 
                         'fail db write compare')
 

	
 
        self.checkSessionFlash(response,
 
                               'Ldap settings updated successfully')
 

	
 
    def test_ldap_error_form(self):
 
        self.log_user()
 
        if skip_ldap_test:
 
            raise SkipTest('skipping due to missing ldap lib')
 
                
 
        test_url = url(controller='admin/ldap_settings',
rhodecode/tests/functional/test_admin_notifications.py
Show inline comments
 
from rhodecode.tests import *
 
from rhodecode.model.db import Notification, User, UserNotification
 

	
 
from rhodecode.model.user import UserModel
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.model.meta import Session
 

	
 
class TestNotificationsController(TestController):
 

	
 

	
 
    def tearDown(self):
 
        for n in Notification.query().all():
 
            inst = Notification.get(n.notification_id)
 
            Session().delete(inst)
 
        Session().commit()
 

	
 
    def test_index(self):
 
        self.log_user()
 

	
 

	
 
        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
 
                                               email='u1@rhodecode.org',
 
                                               name='u1', lastname='u1').user_id
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2').user_id
 

	
 
        response = self.app.get(url('notifications'))
 
        self.assertTrue('''<div class="table">No notifications here yet</div>'''
 
                        in response.body)
 

	
 
        cur_user = self._get_logged_user()
 

	
 
        NotificationModel().create(created_by=u1, subject=u'test',
 
        NotificationModel().create(created_by=u1, subject=u'test_notification_1',
 
                                   body=u'notification_1',
 
                                   recipients=[cur_user])
 
        Session().commit()
 
        response = self.app.get(url('notifications'))
 

	
 
        self.assertTrue(u'notification_1' in response.body)
 

	
 
        User.delete(u1)
 
        User.delete(u2)
 
        self.assertTrue(u'test_notification_1' in response.body)
 

	
 
#    def test_index_as_xml(self):
 
#        response = self.app.get(url('formatted_notifications', format='xml'))
 
#
 
#    def test_create(self):
 
#        response = self.app.post(url('notifications'))
 
#
 
#    def test_new(self):
 
#        response = self.app.get(url('new_notification'))
 
#
 
#    def test_new_as_xml(self):
 
#        response = self.app.get(url('formatted_new_notification', format='xml'))
 
@@ -53,65 +54,66 @@ class TestNotificationsController(TestCo
 

	
 
    def test_delete(self):
 
        self.log_user()
 
        cur_user = self._get_logged_user()
 

	
 
        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
 
                                               email='u1@rhodecode.org',
 
                                               name='u1', lastname='u1')
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2')
 

	
 
        # make two notifications 
 
        # make notifications
 
        notification = NotificationModel().create(created_by=cur_user,
 
                                                  subject=u'test',
 
                                                  body=u'hi there',
 
                                                  recipients=[cur_user, u1, u2])
 

	
 
        Session().commit()
 
        u1 = User.get(u1.user_id)
 
        u2 = User.get(u2.user_id)
 

	
 
        # check DB
 
        self.assertEqual(u1.notifications, [notification])
 
        self.assertEqual(u2.notifications, [notification])
 
        get_notif = lambda un:[x.notification for x in un]
 
        self.assertEqual(get_notif(cur_user.notifications), [notification])
 
        self.assertEqual(get_notif(u1.notifications), [notification])
 
        self.assertEqual(get_notif(u2.notifications), [notification])
 
        cur_usr_id = cur_user.user_id
 
        response = self.app.delete(url('notification',
 
                                       notification_id=cur_usr_id))
 

	
 

	
 
        cur_user = self._get_logged_user()
 
        self.assertEqual(cur_user.notifications, [])
 
        response = self.app.delete(url('notification',
 
                                       notification_id=
 
                                       notification.notification_id))
 

	
 
        User.delete(u1.user_id)
 
        User.delete(u2.user_id)
 
        cur_user = User.get(cur_usr_id)
 
        self.assertEqual(cur_user.notifications, [])
 

	
 

	
 
#    def test_delete_browser_fakeout(self):
 
#        response = self.app.post(url('notification', notification_id=1), params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
        self.log_user()
 
        cur_user = self._get_logged_user()
 
        u1 = UserModel().create_or_update(username='u1', password='qweqwe',
 
                                               email='u1@rhodecode.org',
 
                                               name='u1', lastname='u1')
 
        u2 = UserModel().create_or_update(username='u2', password='qweqwe',
 
                                               email='u2@rhodecode.org',
 
                                               name='u2', lastname='u2')
 

	
 
        notification = NotificationModel().create(created_by=cur_user,
 
                                                  subject='test',
 
                                                  body='hi there',
 
                                                  body=u'hi there',
 
                                                  recipients=[cur_user, u1, u2])
 

	
 
        response = self.app.get(url('notification',
 
                                    notification_id=notification.notification_id))
 

	
 
#    def test_show_as_xml(self):
 
#        response = self.app.get(url('formatted_notification', notification_id=1, format='xml'))
 
#
 
#    def test_edit(self):
 
#        response = self.app.get(url('edit_notification', notification_id=1))
 
#
 
#    def test_edit_as_xml(self):
 
#        response = self.app.get(url('formatted_edit_notification', notification_id=1, format='xml'))
 

	
rhodecode/tests/functional/test_admin_repos.py
Show inline comments
 
@@ -27,25 +27,25 @@ class TestAdminReposController(TestContr
 
        description = 'description for newly created repo'
 
        private = False
 
        response = self.app.post(url('repos'), {'repo_name':repo_name,
 
                                                'repo_type':'hg',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 

	
 
        self.checkSessionFlash(response, 'created repository %s' % (repo_name))
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
                                                    repo_name).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name)
 
        self.assertEqual(new_repo.description, description)
 

	
 
        #test if repository is visible in the list ?
 
        response = response.follow()
 

	
 
        self.assertTrue(repo_name in response.body)
 

	
 

	
 
        #test if repository was created on filesystem
 
@@ -64,25 +64,25 @@ class TestAdminReposController(TestContr
 
        description_unicode = description.decode('utf8')
 
        private = False
 
        response = self.app.post(url('repos'), {'repo_name':repo_name,
 
                                                'repo_type':'hg',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 
        self.checkSessionFlash(response,
 
                               'created repository %s' % (repo_name_unicode))
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
                                                repo_name_unicode).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name_unicode)
 
        self.assertEqual(new_repo.description, description_unicode)
 

	
 
        #test if repository is visible in the list ?
 
        response = response.follow()
 

	
 
        self.assertTrue(repo_name in response.body)
 

	
 
        #test if repository was created on filesystem
 
        try:
 
@@ -104,25 +104,25 @@ class TestAdminReposController(TestContr
 
        response = self.app.post(url('repos'), {'repo_name':repo_name,
 
                                                'repo_type':'git',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 

	
 

	
 
        #test if we have a message for that repository
 
        assert '''created repository %s''' % (repo_name) in response.session['flash'][0], 'No flash message about new repo'
 

	
 
        #test if the fork was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name == repo_name).one()
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name == repo_name).one()
 

	
 
        assert new_repo.repo_name == repo_name, 'wrong name of repo name in db'
 
        assert new_repo.description == description, 'wrong description'
 

	
 
        #test if repository is visible in the list ?
 
        response = response.follow()
 

	
 
        assert repo_name in response.body, 'missing new repo from the main repos list'
 

	
 
        #test if repository was created on filesystem
 
        try:
 
            vcs.get_repo(os.path.join(TESTS_TMP_PATH, repo_name))
 
@@ -153,45 +153,45 @@ class TestAdminReposController(TestContr
 
                                                'repo_type':'hg',
 
                                                'clone_uri':'',
 
                                                'repo_group':'',
 
                                                'description':description,
 
                                                'private':private})
 
        self.assertTrue('flash' in response.session)
 

	
 
        #test if we have a message for that repository
 
        self.assertTrue('''created repository %s''' % (repo_name) in
 
                        response.session['flash'][0])
 

	
 
        #test if the repo was created in the database
 
        new_repo = self.sa.query(Repository).filter(Repository.repo_name ==
 
        new_repo = self.Session().query(Repository).filter(Repository.repo_name ==
 
                                                    repo_name).one()
 

	
 
        self.assertEqual(new_repo.repo_name, repo_name)
 
        self.assertEqual(new_repo.description, description)
 

	
 
        #test if repository is visible in the list ?
 
        response = response.follow()
 

	
 
        self.assertTrue(repo_name in response.body)
 

	
 

	
 
        response = self.app.delete(url('repo', repo_name=repo_name))
 

	
 
        self.assertTrue('''deleted repository %s''' % (repo_name) in
 
                        response.session['flash'][0])
 

	
 
        response.follow()
 

	
 
        #check if repo was deleted from db
 
        deleted_repo = self.sa.query(Repository).filter(Repository.repo_name
 
        deleted_repo = self.Session().query(Repository).filter(Repository.repo_name
 
                                                        == repo_name).scalar()
 

	
 
        self.assertEqual(deleted_repo, None)
 

	
 

	
 
    def test_delete_repo_with_group(self):
 
        #TODO:
 
        pass
 

	
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('repo', repo_name=HG_REPO),
rhodecode/tests/functional/test_admin_settings.py
Show inline comments
 
@@ -136,25 +136,25 @@ class TestAdminSettingsController(TestCo
 
        response = self.app.post(url('admin_settings_my_account_update'),
 
                                 params=dict(_method='put',
 
                                             username='test_admin',
 
                                             new_password=new_password,
 
                                             password_confirmation = new_password,
 
                                             password='',
 
                                             name=new_name,
 
                                             lastname=new_lastname,
 
                                             email=new_email,))
 
        response.follow()
 

	
 
        assert 'Your account was updated successfully' in response.session['flash'][0][1], 'no flash message about success of change'
 
        user = self.sa.query(User).filter(User.username == 'test_admin').one()
 
        user = self.Session().query(User).filter(User.username == 'test_admin').one()
 
        assert user.email == new_email , 'incorrect user email after update got %s vs %s' % (user.email, new_email)
 
        assert user.name == new_name, 'updated field mismatch %s vs %s' % (user.name, new_name)
 
        assert user.lastname == new_lastname, 'updated field mismatch %s vs %s' % (user.lastname, new_lastname)
 
        assert check_password(new_password, user.password) is True, 'password field mismatch %s vs %s' % (user.password, new_password)
 

	
 
        #bring back the admin settings
 
        old_email = 'test_admin@mail.com'
 
        old_name = 'RhodeCode'
 
        old_lastname = 'Admin'
 
        old_password = 'test12'
 

	
 
        response = self.app.post(url('admin_settings_my_account_update'), params=dict(
 
@@ -162,25 +162,25 @@ class TestAdminSettingsController(TestCo
 
                                                            username='test_admin',
 
                                                            new_password=old_password,
 
                                                            password_confirmation = old_password,
 
                                                            password='',
 
                                                            name=old_name,
 
                                                            lastname=old_lastname,
 
                                                            email=old_email,))
 

	
 
        response.follow()
 
        self.checkSessionFlash(response,
 
                               'Your account was updated successfully')
 

	
 
        user = self.sa.query(User).filter(User.username == 'test_admin').one()
 
        user = self.Session().query(User).filter(User.username == 'test_admin').one()
 
        assert user.email == old_email , 'incorrect user email after update got %s vs %s' % (user.email, old_email)
 

	
 
        assert user.email == old_email , 'incorrect user email after update got %s vs %s' % (user.email, old_email)
 
        assert user.name == old_name, 'updated field mismatch %s vs %s' % (user.name, old_name)
 
        assert user.lastname == old_lastname, 'updated field mismatch %s vs %s' % (user.lastname, old_lastname)
 
        assert check_password(old_password, user.password) is True , 'password updated field mismatch %s vs %s' % (user.password, old_password)
 

	
 

	
 
    def test_my_account_update_err_email_exists(self):
 
        self.log_user()
 

	
 
        new_email = 'test_regular@mail.com'#already exisitn email
rhodecode/tests/functional/test_admin_users.py
Show inline comments
 
@@ -23,25 +23,25 @@ class TestAdminUsersController(TestContr
 

	
 
        response = self.app.post(url('users'), {'username':username,
 
                                               'password':password,
 
                                               'password_confirmation':password_confirmation,
 
                                               'name':name,
 
                                               'active':True,
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 

	
 
        assert '''created user %s''' % (username) in response.session['flash'][0], 'No flash message about new user'
 

	
 
        new_user = self.sa.query(User).filter(User.username == username).one()
 
        new_user = self.Session().query(User).filter(User.username == username).one()
 

	
 

	
 
        assert new_user.username == username, 'wrong info about username'
 
        assert check_password(password, new_user.password) == True , 'wrong info about password'
 
        assert new_user.name == name, 'wrong info about name'
 
        assert new_user.lastname == lastname, 'wrong info about lastname'
 
        assert new_user.email == email, 'wrong info about email'
 

	
 

	
 
        response.follow()
 
        response = response.follow()
 
        assert """edit">newtestuser</a>""" in response.body
 
@@ -57,25 +57,25 @@ class TestAdminUsersController(TestContr
 
        response = self.app.post(url('users'), {'username':username,
 
                                               'password':password,
 
                                               'name':name,
 
                                               'active':False,
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 
        assert """<span class="error-message">Invalid username</span>""" in response.body
 
        assert """<span class="error-message">Please enter a value</span>""" in response.body
 
        assert """<span class="error-message">An email address must contain a single @</span>""" in response.body
 

	
 
        def get_user():
 
            self.sa.query(User).filter(User.username == username).one()
 
            self.Session().query(User).filter(User.username == username).one()
 

	
 
        self.assertRaises(NoResultFound, get_user), 'found user in database'
 

	
 
    def test_new(self):
 
        response = self.app.get(url('new_user'))
 

	
 
    def test_new_as_xml(self):
 
        response = self.app.get(url('formatted_new_user', format='xml'))
 

	
 
    def test_update(self):
 
        response = self.app.put(url('user', id=1))
 

	
 
@@ -91,25 +91,25 @@ class TestAdminUsersController(TestContr
 
        email = 'todeletemail@mail.com'
 

	
 
        response = self.app.post(url('users'), {'username':username,
 
                                               'password':password,
 
                                               'password_confirmation':password,
 
                                               'name':name,
 
                                               'active':True,
 
                                               'lastname':lastname,
 
                                               'email':email})
 

	
 
        response = response.follow()
 

	
 
        new_user = self.sa.query(User).filter(User.username == username).one()
 
        new_user = self.Session().query(User).filter(User.username == username).one()
 
        response = self.app.delete(url('user', id=new_user.user_id))
 

	
 
        assert """successfully deleted user""" in response.session['flash'][0], 'No info about user deletion'
 

	
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('user', id=1), params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
        response = self.app.get(url('user', id=1))
 

	
 
    def test_show_as_xml(self):
rhodecode/tests/functional/test_admin_users_groups.py
Show inline comments
 
@@ -43,31 +43,31 @@ class TestAdminUsersGroupsController(Tes
 
    def test_delete(self):
 
        self.log_user()
 
        users_group_name = TEST_USERS_GROUP + 'another'
 
        response = self.app.post(url('users_groups'),
 
                                 {'users_group_name':users_group_name,
 
                                  'active':True})
 
        response.follow()
 

	
 
        self.checkSessionFlash(response,
 
                               'created users group %s' % users_group_name)
 

	
 

	
 
        gr = self.sa.query(UsersGroup)\
 
        gr = self.Session().query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
                                   users_group_name).one()
 

	
 
        response = self.app.delete(url('users_group', id=gr.users_group_id))
 

	
 
        gr = self.sa.query(UsersGroup)\
 
        gr = self.Session().query(UsersGroup)\
 
                           .filter(UsersGroup.users_group_name ==
 
                                   users_group_name).scalar()
 

	
 
        self.assertEqual(gr, None)
 

	
 

	
 
    def test_delete_browser_fakeout(self):
 
        response = self.app.post(url('users_group', id=1),
 
                                 params=dict(_method='delete'))
 

	
 
    def test_show(self):
 
        response = self.app.get(url('users_group', id=1))
rhodecode/tests/functional/test_journal.py
Show inline comments
 
@@ -7,28 +7,28 @@ class TestJournalController(TestControll
 

	
 
    def test_index(self):
 
        self.log_user()
 
        response = self.app.get(url(controller='journal', action='index'))
 

	
 
        # Test response...
 
        assert """ <span id="follow_toggle_1" class="following" title="Stop following this repository""" in response.body, 'no info about stop follwoing repo id 1'
 

	
 
        assert """<div class="journal_day">%s</div>""" % datetime.date.today() in response.body, 'no info about action journal day'
 

	
 
    def test_stop_following_repository(self):
 
        session = self.log_user()
 
#        usr = self.sa.query(User).filter(User.username == 'test_admin').one()
 
#        repo = self.sa.query(Repository).filter(Repository.repo_name == HG_REPO).one()
 
#        usr = self.Session().query(User).filter(User.username == 'test_admin').one()
 
#        repo = self.Session().query(Repository).filter(Repository.repo_name == HG_REPO).one()
 
#
 
#        followings = self.sa.query(UserFollowing)\
 
#        followings = self.Session().query(UserFollowing)\
 
#            .filter(UserFollowing.user == usr)\
 
#            .filter(UserFollowing.follows_repository == repo).all()
 
#
 
#        assert len(followings) == 1, 'Not following any repository'
 
#
 
#        response = self.app.post(url(controller='journal',
 
#                                     action='toggle_following'),
 
#                                     {'auth_token':get_token(session),
 
#                                      'follows_repo_id':repo.repo_id})
 

	
 
    def test_start_following_repository(self):
 
        self.log_user()
rhodecode/tests/functional/test_login.py
Show inline comments
 
@@ -183,25 +183,25 @@ class TestLoginController(TestController
 
        lastname = 'testlastname'
 

	
 
        response = self.app.post(url(controller='login', action='register'),
 
                                            {'username':username,
 
                                             'password':password,
 
                                             'password_confirmation':password,
 
                                             'email':email,
 
                                             'name':name,
 
                                             'lastname':lastname})
 
        self.assertEqual(response.status , '302 Found')
 
        assert 'You have successfully registered into rhodecode' in response.session['flash'][0], 'No flash message about user registration'
 

	
 
        ret = self.sa.query(User).filter(User.username == 'test_regular4').one()
 
        ret = self.Session().query(User).filter(User.username == 'test_regular4').one()
 
        assert ret.username == username , 'field mismatch %s %s' % (ret.username, username)
 
        assert check_password(password, ret.password) == True , 'password mismatch'
 
        assert ret.email == email , 'field mismatch %s %s' % (ret.email, email)
 
        assert ret.name == name , 'field mismatch %s %s' % (ret.name, name)
 
        assert ret.lastname == lastname , 'field mismatch %s %s' % (ret.lastname, lastname)
 

	
 

	
 
    def test_forgot_password_wrong_mail(self):
 
        response = self.app.post(url(controller='login', action='password_reset'),
 
                                            {'email':'marcin@wrongmail.org', })
 

	
 
        assert "This e-mail address doesn't exist" in response.body, 'Missing error message about wrong email'
 
@@ -215,26 +215,26 @@ class TestLoginController(TestController
 
        password = 'qweqwe'
 
        email = 'marcin@python-works.com'
 
        name = 'passwd'
 
        lastname = 'reset'
 

	
 
        new = User()
 
        new.username = username
 
        new.password = password
 
        new.email = email
 
        new.name = name
 
        new.lastname = lastname
 
        new.api_key = generate_api_key(username)
 
        self.sa.add(new)
 
        self.sa.commit()
 
        self.Session().add(new)
 
        self.Session().commit()
 

	
 
        response = self.app.post(url(controller='login',
 
                                     action='password_reset'),
 
                                 {'email':email, })
 

	
 
        self.checkSessionFlash(response, 'Your password reset link was sent')
 

	
 
        response = response.follow()
 

	
 
        # BAD KEY
 

	
 
        key = "bad"
rhodecode/tests/functional/test_settings.py
Show inline comments
 
@@ -23,25 +23,25 @@ class TestSettingsController(TestControl
 
        response = self.app.post(url(controller='settings', action='fork_create',
 
                                    repo_name=repo_name),
 
                                    {'fork_name':fork_name,
 
                                     'repo_type':'hg',
 
                                     'description':description,
 
                                     'private':'False'})
 

	
 
        #test if we have a message that fork is ok
 
        assert 'forked %s repository as %s' \
 
                      % (repo_name, fork_name) in response.session['flash'][0], 'No flash message about fork'
 

	
 
        #test if the fork was created in the database
 
        fork_repo = self.sa.query(Repository).filter(Repository.repo_name == fork_name).one()
 
        fork_repo = self.Session().query(Repository).filter(Repository.repo_name == fork_name).one()
 

	
 
        assert fork_repo.repo_name == fork_name, 'wrong name of repo name in new db fork repo'
 
        assert fork_repo.fork.repo_name == repo_name, 'wrong fork parrent'
 

	
 

	
 
        #test if fork is visible in the list ?
 
        response = response.follow()
 

	
 

	
 
        #check if fork is marked as fork
 
        response = self.app.get(url(controller='summary', action='index',
 
                                    repo_name=fork_name))
rhodecode/tests/functional/test_summary.py
Show inline comments
 
@@ -34,14 +34,14 @@ class TestSummaryController(TestControll
 
                        """"Makefile"]}, "cfg": {"count": 1, "desc": ["Ini"]},"""
 
                        """ "css": {"count": 1, "desc": ["Css"]}, "bat": """
 
                        """{"count": 1, "desc": ["Batch"]}};"""
 
                        in response.body)
 

	
 
        # clone url...
 
        self.assertTrue("""<input type="text" id="clone_url" readonly="readonly" value="hg clone http://test_admin@localhost:80/%s" size="70"/>""" % HG_REPO in response.body)
 

	
 

	
 
    def _enable_stats(self):
 
        r = Repository.get_by_repo_name(HG_REPO)
 
        r.enable_statistics = True
 
        self.sa.add(r)
 
        self.sa.commit()
 
        self.Session().add(r)
 
        self.Session().commit()
rhodecode/tests/test_libs.py
Show inline comments
 
@@ -94,12 +94,23 @@ class TestLibs(unittest.TestCase):
 
            ('TRUE', True),
 
            ('T', True),
 
            ('False', False),
 
            ('F', False),
 
            ('FALSE', False),
 
            ('0', False),
 
            ('-1', False),
 
            ('', False), ]
 

	
 
        for case in test_cases:
 
            self.assertEqual(str2bool(case[0]), case[1])
 

	
 

	
 
    def test_mention_extractor(self):
 
        from rhodecode.lib import extract_mentioned_users
 
        sample = ("@first hi there @marcink here's my email marcin@email.com "
 
                  "@lukaszb check it pls @ ttwelve @D[] @one@two@three "
 
                  "@MARCIN    @maRCiN @2one_more22")
 
        s = ['2one_more22', 'D', 'MARCIN', 'first', 'lukaszb',
 
             'maRCiN', 'marcink', 'one']
 
        self.assertEqual(s, extract_mentioned_users(sample))
 

	
 

	
rhodecode/tests/test_models.py
Show inline comments
 
import os
 
import unittest
 
from rhodecode.tests import *
 

	
 
from rhodecode.model.repos_group import ReposGroupModel
 
from rhodecode.model.repo import RepoModel
 
from rhodecode.model.db import RepoGroup, User, Notification, UserNotification
 
from rhodecode.model.db import RepoGroup, User, Notification, UserNotification, \
 
    UsersGroup, UsersGroupMember
 
from sqlalchemy.exc import IntegrityError
 
from rhodecode.model.user import UserModel
 

	
 
from rhodecode.model import meta
 

	
 
Session = meta.Session()
 
from rhodecode.model.meta import Session
 
from rhodecode.model.notification import NotificationModel
 
from rhodecode.model.users_group import UsersGroupModel
 

	
 
class TestReposGroups(unittest.TestCase):
 

	
 
    def setUp(self):
 
        self.g1 = self.__make_group('test1', skip_if_exists=True)
 
        self.g2 = self.__make_group('test2', skip_if_exists=True)
 
        self.g3 = self.__make_group('test3', skip_if_exists=True)
 

	
 
    def tearDown(self):
 
        print 'out'
 

	
 
    def __check_path(self, *path):
 
@@ -146,80 +147,183 @@ class TestReposGroups(unittest.TestCase)
 
        form_data['perms_new'] = []
 
        form_data['perms_updates'] = []
 
        RepoModel().update(r.repo_name, form_data)
 
        self.assertEqual(r.repo_name, 'g1/john')
 

	
 

	
 
        self.__update_group(g1.group_id, 'g1', parent_id=g2.group_id)
 
        self.assertTrue(self.__check_path('g2', 'g1'))
 

	
 
        # test repo
 
        self.assertEqual(r.repo_name, os.path.join('g2', 'g1', r.just_name))
 

	
 
class TestUser(unittest.TestCase):
 

	
 
    def test_create_and_remove(self):
 
        usr = UserModel().create_or_update(username=u'test_user', password=u'qweqwe',
 
                                     email=u'u232@rhodecode.org',
 
                                     name=u'u1', lastname=u'u1')
 
        self.assertEqual(User.get_by_username(u'test_user'), usr)
 

	
 
        # make users group
 
        users_group = UsersGroupModel().create_('some_example_group')
 
        Session().commit()
 
        UsersGroupModel().add_user_to_group(users_group, usr)
 

	
 
        self.assertEqual(UsersGroup.get(users_group.users_group_id), users_group)
 
        self.assertEqual(UsersGroupMember.query().count(), 1)
 
        UserModel().delete(usr.user_id)
 

	
 
        self.assertEqual(UsersGroupMember.query().all(), [])
 

	
 

	
 
class TestNotifications(unittest.TestCase):
 

	
 

	
 
    def __init__(self, methodName='runTest'):
 
        self.u1 = UserModel().create_or_update(username=u'u1',
 
                                        password=u'qweqwe',
 
                                        email=u'u1@rhodecode.org',
 
                                        name=u'u1', lastname=u'u1').user_id
 
        self.u2 = UserModel().create_or_update(username=u'u2',
 
                                        password=u'qweqwe',
 
                                        email=u'u2@rhodecode.org',
 
                                        name=u'u2', lastname=u'u3').user_id
 
        self.u3 = UserModel().create_or_update(username=u'u3',
 
                                        password=u'qweqwe',
 
                                        email=u'u3@rhodecode.org',
 
                                        name=u'u3', lastname=u'u3').user_id
 
        super(TestNotifications, self).__init__(methodName=methodName)
 

	
 
    def setUp(self):
 
        self.u1 = UserModel().create_or_update(username=u'u1', password=u'qweqwe',
 
                                               email=u'u1@rhodecode.org',
 
                                               name=u'u1', lastname=u'u1')
 
        self.u2 = UserModel().create_or_update(username=u'u2', password=u'qweqwe',
 
                                               email=u'u2@rhodecode.org',
 
                                               name=u'u2', lastname=u'u3')
 
        self.u3 = UserModel().create_or_update(username=u'u3', password=u'qweqwe',
 
                                               email=u'u3@rhodecode.org',
 
                                               name=u'u3', lastname=u'u3')
 
    def tearDown(self):
 
        User.delete(self.u1.user_id)
 
        User.delete(self.u2.user_id)
 
        User.delete(self.u3.user_id)
 
    def _clean_notifications(self):
 
        for n in Notification.query().all():
 
            Session().delete(n)
 

	
 
        Session().commit()
 
        self.assertEqual(Notification.query().all(), [])
 

	
 

	
 
    def test_create_notification(self):
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        usrs = [self.u1, self.u2]
 
        notification = Notification.create(created_by=self.u1,
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'subj', body=u'hi there',
 
                                           recipients=usrs)
 
        Session.commit()
 

	
 

	
 
        Session().commit()
 
        u1 = User.get(self.u1)
 
        u2 = User.get(self.u2)
 
        u3 = User.get(self.u3)
 
        notifications = Notification.query().all()
 
        self.assertEqual(len(notifications), 1)
 

	
 
        unotification = UserNotification.query()\
 
            .filter(UserNotification.notification == notification).all()
 

	
 
        self.assertEqual(notifications[0].recipients, [self.u1, self.u2])
 
        self.assertEqual(notifications[0].recipients, [u1, u2])
 
        self.assertEqual(notification.notification_id,
 
                         notifications[0].notification_id)
 
        self.assertEqual(len(unotification), len(usrs))
 
        self.assertEqual([x.user.user_id for x in unotification],
 
                         [x.user_id for x in usrs])
 
        self.assertEqual([x.user.user_id for x in unotification], usrs)
 

	
 
        self._clean_notifications()
 

	
 
    def test_user_notifications(self):
 
        notification1 = Notification.create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there',
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        notification1 = NotificationModel().create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there1',
 
                                            recipients=[self.u3])
 
        notification2 = Notification.create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there',
 
        Session().commit()
 
        notification2 = NotificationModel().create(created_by=self.u1,
 
                                            subject=u'subj', body=u'hi there2',
 
                                            recipients=[self.u3])
 
        self.assertEqual(self.u3.notifications, [notification1, notification2])
 
        Session().commit()
 
        u3 = Session().query(User).get(self.u3)
 

	
 
        self.assertEqual(sorted([x.notification for x in u3.notifications]),
 
                         sorted([notification2, notification1]))
 
        self._clean_notifications()
 

	
 
    def test_delete_notifications(self):
 
        notification = Notification.create(created_by=self.u1,
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'title', body=u'hi there3',
 
                                    recipients=[self.u3, self.u1, self.u2])
 
        Session.commit()
 
        Session().commit()
 
        notifications = Notification.query().all()
 
        self.assertTrue(notification in notifications)
 

	
 
        Notification.delete(notification.notification_id)
 
        Session.commit()
 
        Session().commit()
 

	
 
        notifications = Notification.query().all()
 
        self.assertFalse(notification in notifications)
 

	
 
        un = UserNotification.query().filter(UserNotification.notification
 
                                             == notification).all()
 
        self.assertEqual(un, [])
 

	
 
        self._clean_notifications()
 
    def test_delete_association(self):
 

	
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'title', body=u'hi there3',
 
                                    recipients=[self.u3, self.u1, self.u2])
 
        Session().commit()
 

	
 
        unotification = UserNotification.query()\
 
                            .filter(UserNotification.notification ==
 
                                    notification)\
 
                            .filter(UserNotification.user_id == self.u3)\
 
                            .scalar()
 

	
 
        self.assertEqual(unotification.user_id, self.u3)
 

	
 
        NotificationModel().delete(self.u3,
 
                                   notification.notification_id)
 
        Session().commit()
 

	
 
        unotification = UserNotification.query()\
 
                            .filter(UserNotification.notification ==
 
                                    notification)\
 
                            .filter(UserNotification.user_id == self.u3)\
 
                            .scalar()
 

	
 
        self.assertEqual(unotification, None)
 
        self._clean_notifications()
 

	
 
    def test_notification_counter(self):
 
        self._clean_notifications()
 
        self.assertEqual([], Notification.query().all())
 
        self.assertEqual([], UserNotification.query().all())
 

	
 
        NotificationModel().create(created_by=self.u1,
 
                            subject=u'title', body=u'hi there_delete',
 
                            recipients=[self.u3, self.u1])
 
        Session().commit()
 

	
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u1), 1)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u2), 0)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u3), 1)
 

	
 
        notification = NotificationModel().create(created_by=self.u1,
 
                                           subject=u'title', body=u'hi there3',
 
                                    recipients=[self.u3, self.u1, self.u2])
 
        Session().commit()
 

	
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u1), 2)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u2), 1)
 
        self.assertEqual(NotificationModel()
 
                         .get_unread_cnt_for_user(self.u3), 2)
 
        self._clean_notifications()
0 comments (0 inline, 0 general)