Exemplo n.º 1
0
    def add_event(
        self,
        calendar: Calendar,
        event: iCalendarEvent,
        event_name: str,
        owner: User,
    ) -> Content:
        """
        Create Content event type.
        :param calendar: Event calendar owner
        :param event: ICS event
        :param event_name: Event name (ID) like
        20160602T083511Z-18100-1001-1-71_Bastien-20160602T083516Z.ics
        :param owner: Event Owner
        :return: Created Content
        """
        workspace = None
        if isinstance(calendar, WorkspaceCalendar):
            workspace = calendar.related_object
        elif isinstance(calendar, UserCalendar):
            pass
        else:
            raise UnknownCalendarType('Type "{0}" is not implemented'.format(
                type(calendar)))

        content = ContentApi(owner).create(content_type=ContentType.Event,
                                           workspace=workspace,
                                           do_save=False)
        self.populate_content_with_event(content, event, event_name)
        content.revision_type = ActionDescription.CREATION
        DBSession.add(content)
        DBSession.flush()
        transaction.commit()

        return content
Exemplo n.º 2
0
    def create(self,
               content_type: str,
               workspace: Workspace,
               parent: Content = None,
               label: str = '',
               do_save=False,
               is_temporary: bool = False) -> Content:
        assert content_type in ContentType.allowed_types()

        if content_type == ContentType.Folder and not label:
            label = self.generate_folder_label(workspace, parent)

        content = Content()
        content.owner = self._user
        content.parent = parent
        content.workspace = workspace
        content.type = content_type
        content.label = label
        content.is_temporary = is_temporary
        content.revision_type = ActionDescription.CREATION

        if content.type in (
                ContentType.Page,
                ContentType.Thread,
        ):
            content.file_extension = '.html'

        if do_save:
            DBSession.add(content)
            self.save(content, ActionDescription.CREATION)
        return content
Exemplo n.º 3
0
    def create_workspace(
        self,
        label: str = '',
        description: str = '',
        calendar_enabled: bool = False,
        save_now: bool = False,
    ) -> Workspace:
        if not label:
            label = self.generate_label()

        workspace = Workspace()
        workspace.label = label
        workspace.description = description
        workspace.calendar_enabled = calendar_enabled

        # By default, we force the current user to be the workspace manager
        # And to receive email notifications
        role = RoleApi(self._user).create_one(
            self._user,
            workspace,
            UserRoleInWorkspace.WORKSPACE_MANAGER,
            with_notif=True)

        DBSession.add(workspace)
        DBSession.add(role)

        if save_now:
            DBSession.flush()

        if calendar_enabled:
            self.ensure_calendar_exist(workspace)
        else:
            self.disable_calendar(workspace)

        return workspace
Exemplo n.º 4
0
    def create(self, content_type: str, workspace: Workspace, parent: Content=None, label:str ='', do_save=False, is_temporary: bool=False) -> Content:
        assert content_type in ContentType.allowed_types()

        if content_type == ContentType.Folder and not label:
            label = self.generate_folder_label(workspace, parent)

        content = Content()
        content.owner = self._user
        content.parent = parent
        content.workspace = workspace
        content.type = content_type
        content.label = label
        content.is_temporary = is_temporary
        content.revision_type = ActionDescription.CREATION

        if content.type in (
                ContentType.Page,
                ContentType.Thread,
        ):
            content.file_extension = '.html'

        if do_save:
            DBSession.add(content)
            self.save(content, ActionDescription.CREATION)
        return content
Exemplo n.º 5
0
    def test_creates(self):
        eq_(
            0,
            DBSession.query(ContentRevisionRO).filter(
                ContentRevisionRO.label == 'TEST_CONTENT_1').count())
        eq_(
            0,
            DBSession.query(Workspace).filter(
                Workspace.label == 'TEST_WORKSPACE_1').count())

        user_admin = DBSession.query(User).filter(
            User.email == '*****@*****.**').one()
        workspace = Workspace(label="TEST_WORKSPACE_1")
        DBSession.add(workspace)
        DBSession.flush()
        eq_(
            1,
            DBSession.query(Workspace).filter(
                Workspace.label == 'TEST_WORKSPACE_1').count())

        first_content = self._create_content(
            owner=user_admin,
            workspace=workspace,
            type=ContentType.Page,
            label='TEST_CONTENT_1',
            description='TEST_CONTENT_DESCRIPTION_1',
            revision_type=ActionDescription.CREATION,
            is_deleted=False,  # TODO: pk ?
            is_archived=False,  # TODO: pk ?
            # file_content=None,  # TODO: pk ? (J'ai du mettre nullable=True)
        )

        eq_(
            1,
            DBSession.query(ContentRevisionRO).filter(
                ContentRevisionRO.label == 'TEST_CONTENT_1').count())

        content = DBSession.query(Content).filter(
            Content.id == first_content.id).one()
        eq_('TEST_CONTENT_1', content.label)
        eq_('TEST_CONTENT_DESCRIPTION_1', content.description)

        # Create a second content
        second_content = self._create_content(
            owner=user_admin,
            workspace=workspace,
            type=ContentType.Page,
            label='TEST_CONTENT_2',
            description='TEST_CONTENT_DESCRIPTION_2',
            revision_type=ActionDescription.CREATION)

        eq_(
            1,
            DBSession.query(ContentRevisionRO).filter(
                ContentRevisionRO.label == 'TEST_CONTENT_2').count())

        content = DBSession.query(Content).filter(
            Content.id == second_content.id).one()
        eq_('TEST_CONTENT_2', content.label)
        eq_('TEST_CONTENT_DESCRIPTION_2', content.description)
Exemplo n.º 6
0
    def create_workspace(
            self,
            label: str='',
            description: str='',
            calendar_enabled: bool=False,
            save_now: bool=False,
    ) -> Workspace:
        if not label:
            label = self.generate_label()

        workspace = Workspace()
        workspace.label = label
        workspace.description = description
        workspace.calendar_enabled = calendar_enabled

        # By default, we force the current user to be the workspace manager
        # And to receive email notifications
        role = RoleApi(self._user).create_one(self._user, workspace,
                                              UserRoleInWorkspace.WORKSPACE_MANAGER,
                                              with_notif=True)

        DBSession.add(workspace)
        DBSession.add(role)

        if save_now:
            DBSession.flush()

        if calendar_enabled:
            self.ensure_calendar_exist(workspace)
        else:
            self.disable_calendar(workspace)

        return workspace
Exemplo n.º 7
0
    def test_create(self, key='1'):
        eq_(0, DBSession.query(ContentRevisionRO).filter(ContentRevisionRO.label == 'TEST_CONTENT_%s' % key).count())
        eq_(0, DBSession.query(Workspace).filter(Workspace.label == 'TEST_WORKSPACE_%s' % key).count())

        user_admin = DBSession.query(User).filter(User.email == '*****@*****.**').one()
        workspace = Workspace(label="TEST_WORKSPACE_%s" % key)
        DBSession.add(workspace)
        DBSession.flush()
        eq_(1, DBSession.query(Workspace).filter(Workspace.label == 'TEST_WORKSPACE_%s' % key).count())

        created_content = self._create_content(
            owner=user_admin,
            workspace=workspace,
            type=ContentType.Page,
            label='TEST_CONTENT_%s' % key,
            description='TEST_CONTENT_DESCRIPTION_%s' % key,
            revision_type=ActionDescription.CREATION
        )

        eq_(1, DBSession.query(ContentRevisionRO).filter(ContentRevisionRO.label == 'TEST_CONTENT_%s' % key).count())

        content = DBSession.query(Content).filter(Content.id == created_content.id).one()
        eq_('TEST_CONTENT_%s' % key, content.label)
        eq_('TEST_CONTENT_DESCRIPTION_%s' % key, content.description)

        return created_content
Exemplo n.º 8
0
    def _create_content_and_test(self, name, workspace, *args, **kwargs) -> Content:
        """
        All extra parameters (*args, **kwargs) are for Content init
        :return: Created Content instance
        """
        content = Content(*args, **kwargs)
        content.label = name
        content.workspace = workspace
        DBSession.add(content)
        DBSession.flush()

        eq_(1, ContentApi.get_canonical_query().filter(Content.label == name).count())
        return ContentApi.get_canonical_query().filter(Content.label == name).one()
Exemplo n.º 9
0
    def _create_content_and_test(self, name, workspace, *args, **kwargs) -> Content:
        """
        All extra parameters (*args, **kwargs) are for Content init
        :return: Created Content instance
        """
        content = Content(*args, **kwargs)
        content.label = name
        content.workspace = workspace
        DBSession.add(content)
        DBSession.flush()

        eq_(1, ContentApi.get_canonical_query().filter(Content.label == name).count())
        return ContentApi.get_canonical_query().filter(Content.label == name).one()
Exemplo n.º 10
0
    def create(self, content_type: str, workspace: Workspace, parent: Content=None, label:str ='', do_save=False) -> Content:
        assert content_type in ContentType.allowed_types()
        content = Content()
        content.owner = self._user
        content.parent = parent
        content.workspace = workspace
        content.type = content_type
        content.label = label
        content.revision_type = ActionDescription.CREATION

        if do_save:
            DBSession.add(content)
            self.save(content, ActionDescription.CREATION)
        return content
Exemplo n.º 11
0
    def test_serializer_content__menui_api_context__children(self):
        folder_without_child = Content()
        folder_without_child.type = ContentType.Folder
        res = Context(CTX.MENU_API).toDict(folder_without_child)
        eq_(False, res['children'])

        folder_with_child = Content()
        folder_with_child.type = ContentType.Folder
        folder_without_child.parent = folder_with_child
        DBSession.add(folder_with_child)
        DBSession.add(folder_without_child)
        DBSession.flush()

        res = Context(CTX.MENU_API).toDict(folder_with_child)
        eq_(True, res['children'])

        for curtype in ContentType.all():
            if curtype not in (ContentType.Folder, ContentType.Comment):
                item = Content()
                item.type = curtype

                fake_child = Content()
                fake_child.type = curtype
                fake_child.parent = item

                DBSession.add(item)
                DBSession.add(fake_child)
                DBSession.flush()

                res = Context(CTX.MENU_API).toDict(item)
                eq_(False, res['children'])
Exemplo n.º 12
0
Arquivo: user.py Projeto: qyqx/tracim
    def create_user(self, email=None, groups=[], save_now=False) -> User:
        user = User()

        if email:
            user.email = email

        for group in groups:
            user.groups.append(group)

        DBSession.add(user)

        if save_now:
            DBSession.flush()

        return user
Exemplo n.º 13
0
    def create_workspace(self, label: str, description: str='', save_now:bool=False) -> Workspace:
        workspace = Workspace()
        workspace.label = label
        workspace.description = description

        # By default, we force the current user to be the workspace manager
        # And to receive email notifications
        role = RoleApi(self._user).create_one(self._user, workspace,
                                              UserRoleInWorkspace.WORKSPACE_MANAGER,
                                              with_notif=True)

        DBSession.add(workspace)
        DBSession.add(role)

        if save_now:
            DBSession.flush()

        return workspace
Exemplo n.º 14
0
    def _sync_ldap_user(self, email, environ, identity):
        # Create or get user for connected email
        if not self._user_api.user_with_email_exists(email):
            user = User(email=email, imported_from=LDAPAuth.name)
            DBSession.add(user)
        else:
            user = self._user_api.get_one_by_email(email)

        # Retrieve ldap user attributes
        self._auth.ldap_user_provider.add_metadata_for_auth(environ, identity)

        # Update user with ldap attributes
        user_ldap_values = identity.get('user').copy()
        for field_name in user_ldap_values:
            setattr(user, field_name, user_ldap_values[field_name])

        DBSession.flush()
        transaction.commit()
Exemplo n.º 15
0
Arquivo: ldap.py Projeto: qyqx/tracim
    def _sync_ldap_user(self, email, environ, identity):
        # Create or get user for connected email
        if not self._user_api.user_with_email_exists(email):
            user = User(email=email, imported_from=LDAPAuth.name)
            DBSession.add(user)
        else:
            user = self._user_api.get_one_by_email(email)

        # Retrieve ldap user attributes
        self._auth.ldap_user_provider.add_metadata_for_auth(environ, identity)

        # Update user with ldap attributes
        user_ldap_values = identity.get('user').copy()
        for field_name in user_ldap_values:
            setattr(user, field_name, user_ldap_values[field_name])

        DBSession.flush()
        transaction.commit()
Exemplo n.º 16
0
    def test_create(self):
        DBSession.flush()
        transaction.commit()
        name = 'Damien'
        email = '*****@*****.**'

        user = User()
        user.display_name = name
        user.email = email

        DBSession.add(user)
        DBSession.flush()
        transaction.commit()

        new_user = DBSession.query(User).filter(User.display_name==name).one()

        eq_(new_user.display_name, name)
        eq_(new_user.email, email)
        eq_(new_user.email_address, email)
Exemplo n.º 17
0
    def test_creates(self):
        eq_(0, DBSession.query(ContentRevisionRO).filter(ContentRevisionRO.label == 'TEST_CONTENT_1').count())
        eq_(0, DBSession.query(Workspace).filter(Workspace.label == 'TEST_WORKSPACE_1').count())

        user_admin = DBSession.query(User).filter(User.email == '*****@*****.**').one()
        workspace = Workspace(label="TEST_WORKSPACE_1")
        DBSession.add(workspace)
        DBSession.flush()
        eq_(1, DBSession.query(Workspace).filter(Workspace.label == 'TEST_WORKSPACE_1').count())

        first_content = self._create_content(
            owner=user_admin,
            workspace=workspace,
            type=ContentType.Page,
            label='TEST_CONTENT_1',
            description='TEST_CONTENT_DESCRIPTION_1',
            revision_type=ActionDescription.CREATION,
            is_deleted=False,  # TODO: pk ?
            is_archived=False,  # TODO: pk ?
            #file_content=None,  # TODO: pk ? (J'ai du mettre nullable=True)
        )

        eq_(1, DBSession.query(ContentRevisionRO).filter(ContentRevisionRO.label == 'TEST_CONTENT_1').count())

        content = DBSession.query(Content).filter(Content.id == first_content.id).one()
        eq_('TEST_CONTENT_1', content.label)
        eq_('TEST_CONTENT_DESCRIPTION_1', content.description)

        # Create a second content
        second_content = self._create_content(
            owner=user_admin,
            workspace=workspace,
            type=ContentType.Page,
            label='TEST_CONTENT_2',
            description='TEST_CONTENT_DESCRIPTION_2',
            revision_type=ActionDescription.CREATION
        )

        eq_(1, DBSession.query(ContentRevisionRO).filter(ContentRevisionRO.label == 'TEST_CONTENT_2').count())

        content = DBSession.query(Content).filter(Content.id == second_content.id).one()
        eq_('TEST_CONTENT_2', content.label)
        eq_('TEST_CONTENT_DESCRIPTION_2', content.description)
Exemplo n.º 18
0
    def save(self,
             content: Content,
             action_description: str = None,
             do_flush=True,
             do_notify=True):
        """
        Save an object, flush the session and set the revision_type property
        :param content:
        :param action_description:
        :return:
        """
        assert action_description is None or action_description in ActionDescription.allowed_values(
        )

        if not action_description:
            # See if the last action has been modified
            if content.revision_type == None or len(
                    get_history(content.revision, 'revision_type')) <= 0:
                # The action has not been modified, so we set it to default edition
                action_description = ActionDescription.EDITION

        if action_description:
            content.revision_type = action_description

        if do_flush:
            # INFO - 2015-09-03 - D.A.
            # There are 2 flush because of the use
            # of triggers for content creation
            #
            # (when creating a content, actually this is an insert of a new
            # revision in content_revisions ; so the mark_read operation need
            # to get full real data from database before to be prepared.

            DBSession.add(content)
            DBSession.flush()

            # TODO - 2015-09-03 - D.A. - Do not use triggers
            # We should create a new ContentRevisionRO object instead of Content
            # This would help managing view/not viewed status
            self.mark_read(content, do_flush=True)

        if do_notify:
            self.do_notify(content)
Exemplo n.º 19
0
    def test_create(self):
        DBSession.flush()
        transaction.commit()
        name = 'Damien'
        email = '*****@*****.**'

        user = User()
        user.display_name = name
        user.email = email

        DBSession.add(user)
        DBSession.flush()
        transaction.commit()

        new_user = DBSession.query(User).filter(
            User.display_name == name).one()

        eq_(new_user.display_name, name)
        eq_(new_user.email, email)
        eq_(new_user.email_address, email)
Exemplo n.º 20
0
    def add_event(
            self,
            calendar: Calendar,
            event: iCalendarEvent,
            event_name: str,
            owner: User,
    ) -> Content:
        """
        Create Content event type.
        :param calendar: Event calendar owner
        :param event: ICS event
        :param event_name: Event name (ID) like
        20160602T083511Z-18100-1001-1-71_Bastien-20160602T083516Z.ics
        :param owner: Event Owner
        :return: Created Content
        """
        workspace = None
        if isinstance(calendar, WorkspaceCalendar):
            workspace = calendar.related_object
        elif isinstance(calendar, UserCalendar):
            pass
        else:
            raise UnknownCalendarType('Type "{0}" is not implemented'
                                      .format(type(calendar)))

        content = ContentApi(owner).create(
            content_type=ContentType.Event,
            workspace=workspace,
            do_save=False
        )
        self.populate_content_with_event(
            content,
            event,
            event_name
        )
        content.revision_type = ActionDescription.CREATION
        DBSession.add(content)
        DBSession.flush()
        transaction.commit()

        return content
Exemplo n.º 21
0
    def create(self,
               content_type: str,
               workspace: Workspace,
               parent: Content = None,
               label: str = '',
               is_temporary: bool = False,
               do_save=False) -> Content:
        assert content_type in ContentType.allowed_types()
        content = Content()
        content.owner = self._user
        content.parent = parent
        content.workspace = workspace
        content.type = content_type
        content.label = label
        content.is_temporary = is_temporary
        content.revision_type = ActionDescription.CREATION

        if do_save:
            DBSession.add(content)
            self.save(content, ActionDescription.CREATION)
        return content
Exemplo n.º 22
0
    def create_workspace(self,
                         label: str,
                         description: str = '',
                         save_now: bool = False) -> Workspace:
        workspace = Workspace()
        workspace.label = label
        workspace.description = description

        # By default, we force the current user to be the workspace manager
        # And to receive email notifications
        role = RoleApi(self._user).create_one(
            self._user,
            workspace,
            UserRoleInWorkspace.WORKSPACE_MANAGER,
            with_notif=True)

        DBSession.add(workspace)
        DBSession.add(role)

        if save_now:
            DBSession.flush()

        return workspace
Exemplo n.º 23
0
    def save(self, content: Content, action_description: str=None, do_flush=True, do_notify=True):
        """
        Save an object, flush the session and set the revision_type property
        :param content:
        :param action_description:
        :return:
        """
        assert action_description is None or action_description in ActionDescription.allowed_values()

        if not action_description:
            # See if the last action has been modified
            if content.revision_type==None or len(get_history(content.revision, 'revision_type'))<=0:
                # The action has not been modified, so we set it to default edition
                action_description = ActionDescription.EDITION

        if action_description:
            content.revision_type = action_description

        if do_flush:
            # INFO - 2015-09-03 - D.A.
            # There are 2 flush because of the use
            # of triggers for content creation
            #
            # (when creating a content, actually this is an insert of a new
            # revision in content_revisions ; so the mark_read operation need
            # to get full real data from database before to be prepared.

            DBSession.add(content)
            DBSession.flush()

            # TODO - 2015-09-03 - D.A. - Do not use triggers
            # We should create a new ContentRevisionRO object instead of Content
            # This would help managing view/not viewed status
            self.mark_read(content, do_flush=True)

        if do_notify:
            self.do_notify(content)
Exemplo n.º 24
0
    def test_serializer_content__menui_api_context__children(self):
        folder_without_child = Content()
        folder_without_child.type = ContentType.Folder
        folder_without_child.label = 'folder_without_child'
        res = Context(CTX.MENU_API).toDict(folder_without_child)
        eq_(False, res['children'])

        folder_with_child = Content()
        folder_with_child.type = ContentType.Folder
        folder_with_child.label = 'folder_with_child'
        folder_without_child.parent = folder_with_child
        DBSession.add(folder_with_child)
        DBSession.add(folder_without_child)
        DBSession.flush()

        res = Context(CTX.MENU_API).toDict(folder_with_child)
        eq_(True, res['children'])

        for curtype in ContentType.all():
            if curtype not in (ContentType.Folder, ContentType.Comment,
                               ContentType.Event):
                item = Content()
                item.type = curtype
                item.label = 'item'

                fake_child = Content()
                fake_child.type = curtype
                fake_child.label = 'fake_child'
                fake_child.parent = item

                DBSession.add(item)
                DBSession.add(fake_child)
                DBSession.flush()

                res = Context(CTX.MENU_API).toDict(item)
                eq_(False, res['children'])
Exemplo n.º 25
0
    def create(self, path, lock):
        """Create a direct lock for a resource path.

        path:
            Normalized path (utf8 encoded string, no trailing '/')
        lock:
            lock dictionary, without a token entry
        Returns:
            New unique lock token.: <lock

        **Note:** the lock dictionary may be modified on return:

        - lock['root'] is ignored and set to the normalized <path>
        - lock['timeout'] may be normalized and shorter than requested
        - lock['token'] is added
        """
        self._lock.acquireWrite()
        try:
            # We expect only a lock definition, not an existing lock
            assert lock.get("token") is None
            assert lock.get("expire") is None, "Use timeout instead of expire"
            assert path and "/" in path

            # Normalize root: /foo/bar
            org_path = path
            path = normalizeLockRoot(path)
            lock["root"] = path

            # Normalize timeout from ttl to expire-date
            timeout = float(lock.get("timeout"))
            if timeout is None:
                timeout = LockStorage.LOCK_TIME_OUT_DEFAULT
            elif timeout < 0 or timeout > LockStorage.LOCK_TIME_OUT_MAX:
                timeout = LockStorage.LOCK_TIME_OUT_MAX

            lock["timeout"] = timeout
            lock["expire"] = time.time() + timeout

            validateLock(lock)

            token = generateLockToken()
            lock["token"] = token

            # Store lock
            lock_db = from_dict_to_base(lock)

            DBSession.add(lock_db)

            # Store locked path reference
            url2token = Url2Token(
                path=path,
                token=token
            )

            DBSession.add(url2token)
            transaction.commit()

            self._flush()
            _logger.debug("LockStorageDict.set(%r): %s" % (org_path, lockString(lock)))
            #            print("LockStorageDict.set(%r): %s" % (org_path, lockString(lock)))
            return lock
        finally:
            self._lock.release()
Exemplo n.º 26
0
 def _create_content(self, *args, **kwargs):
     content = Content(*args, **kwargs)
     DBSession.add(content)
     DBSession.flush()
     return content
Exemplo n.º 27
0
    def _create_content(self, *args, **kwargs):
        content = Content(*args, **kwargs)
        DBSession.add(content)
        DBSession.flush()

        return content