Beispiel #1
0
    def modified_requested_recids(self):
        """Record IDs of records that match the filters of this task.

        This property takes (0) `requested_ids`, (1) `filter_pattern` and if
        `force_run_on_unmodified_records` is enabled (2)
        `CheckerRecord.last_run_version_id` into consideration to figure out
        which recids a record-centric task should run on.

        :rtype: intbitset
        """
        # Get all records that are already associated to this rule
        # If this is returning an empty set, you forgot to run bibindex
        try:
            associated_records = intbitset(zip(
                *db.session
                .query(CheckerRecord.rec_id)
                .filter(
                    CheckerRecord.rule_name == self.name
                ).all()
            )[0])
        except IndexError:
            associated_records = intbitset()

        # Store requested records that were until now unknown to this rule
        requested_ids = self.requested_recids
        for requested_id in requested_ids - associated_records:
            new_record = CheckerRecord(rec_id=requested_id,
                                       rule_name=self.name)
            db.session.add(new_record)
        db.session.commit()

        # Figure out which records have been edited since the last time we ran
        # this rule
        try:
            recids = zip(
                *db.session
                .query(CheckerRecord.rec_id)
                .outerjoin(RecordMetadata)
                .filter(
                    CheckerRecord.rec_id.in_(requested_ids),
                    CheckerRecord.rule_name == self.name,
                    db.or_(
                        self.force_run_on_unmodified_records,
                        db.or_(
                            CheckerRecord.last_run_version_id == 1,
                            CheckerRecord.last_run_version_id < RecordMetadata.version_id,
                        ),
                    )
                )
            )[0]
        except IndexError:
            recids = set()
        return intbitset(recids)
Beispiel #2
0
    def modified_requested_recids(self):
        """Record IDs of records that match the filters of this task.

        This property takes (0) `requested_ids`, (1) `filter_pattern` and if
        `force_run_on_unmodified_records` is enabled (2)
        `CheckerRecord.last_run_version_id` into consideration to figure out
        which recids a record-centric task should run on.

        :rtype: intbitset
        """
        # Get all records that are already associated to this rule
        # If this is returning an empty set, you forgot to run bibindex
        try:
            associated_records = intbitset(
                zip(*db.session.query(CheckerRecord.rec_id).filter(
                    CheckerRecord.rule_name == self.name).all())[0])
        except IndexError:
            associated_records = intbitset()

        # Store requested records that were until now unknown to this rule
        requested_ids = self.requested_recids
        for requested_id in requested_ids - associated_records:
            new_record = CheckerRecord(rec_id=requested_id,
                                       rule_name=self.name)
            db.session.add(new_record)
        db.session.commit()

        # Figure out which records have been edited since the last time we ran
        # this rule
        try:
            recids = zip(*db.session.query(CheckerRecord.rec_id).outerjoin(
                RecordMetadata).filter(
                    CheckerRecord.rec_id.in_(requested_ids),
                    CheckerRecord.rule_name == self.name,
                    db.or_(
                        self.force_run_on_unmodified_records,
                        db.or_(
                            CheckerRecord.last_run_version_id == 1,
                            CheckerRecord.last_run_version_id <
                            RecordMetadata.version_id,
                        ),
                    )))[0]
        except IndexError:
            recids = set()
        return intbitset(recids)
Beispiel #3
0
    def generate_slug(name):
        """Generate a slug for the knowledge.

        :param name: text to slugify
        :return: slugified text
        """
        slug = slugify(name)

        i = KnwKB.query.filter(db.or_(
            KnwKB.slug.like(slug),
            KnwKB.slug.like(slug + '-%'),
        )).count()

        return slug + ('-{0}'.format(i) if i > 0 else '')
Beispiel #4
0
    def generate_slug(name):
        """Generate a slug for the knowledge.

        :param name: text to slugify
        :return: slugified text
        """
        slug = slugify(name)

        i = KnwKB.query.filter(
            db.or_(
                KnwKB.slug.like(slug),
                KnwKB.slug.like(slug + '-%'),
            )).count()

        return slug + ('-{0}'.format(i) if i > 0 else '')
Beispiel #5
0
def handle_not_found(exception, **extra):
    """Custom blueprint exception handler."""
    if not isinstance(exception, NotFound):
        return

    page = Page.query.filter(db.or_(Page.url == request.path,
                                    Page.url == request.path + "/")).first()
    if page is not None:
        _add_url_rule(page.url)
        # Modify request to call our errorhandler.
        req_endpoint = request.url_rule.endpoint
        request.url_rule.endpoint = blueprint.name + '.view'

        @after_this_request
        def restore_url_map(response):
            request.url_rule.endpoint = req_endpoint
            return response
Beispiel #6
0
def authenticate(nickname_or_email=None, password=None,
                 login_method=None, remember=False):
    """
    Find user identified by given information and login method.

    :param nickname_or_email: User nickname or email address
    :param password: Password used only in login methods that need it
    :param login_method: Login method (default: 'Local')
    :return: UserInfo
    """
    from invenio_base.i18n import _
    from invenio_ext.sqlalchemy import db
    from invenio_accounts.models import User
    from sqlalchemy.orm.exc import NoResultFound

    where = [db.or_(User.nickname == nickname_or_email,
                    User.email == nickname_or_email)]

    try:
        user = User.query.filter(*where).one()
        if login_method == 'Local' and password is not None:
            if not user.verify_password(password, migrate=True):
                return False
    except NoResultFound:
        return None
    except Exception:
        current_app.logger.exception("Problem checking password.")
        return False

    if login_method is not None and \
            user.settings['login_method'] != login_method:
        flash(_("You are not authorized to use '%(x_login_method)s' login "
                "method.", x_login_method=login_method), 'error')
        return False

    if user.note == '2':  # account is not confirmed
        flash(_("You have not yet verified your email address."), 'warning')

    if user.note == '0':  # account is blocked
        logout_user()
        return False

    if remember:
        session.permanent = True
    return login_user(user.id, remember=remember)
Beispiel #7
0
    def filter_communities(cls, p, so):
        """Search for communities.

        Helper function which takes from database only those communities which
        match search criteria. Uses parameter 'so' to set communities in the
        correct order.

        Parameter 'page' is introduced to restrict results and return only
        slice of them for the current page. If page == 0 function will return
        all communities that match the pattern.
        """
        query = cls.query
        if p:
            query = query.filter(db.or_(
                cls.id.like("%" + p + "%"),
                cls.title.like("%" + p + "%"),
                cls.description.like("%" + p + "%"),
            ))
        if so in cfg['COMMUNITIES_SORTING_OPTIONS']:
            order = so == 'title' and db.asc or db.desc
            query = query.order_by(order(getattr(cls, so)))
        else:
            query = query.order_by(db.desc(cls.ranking))
        return query
def details(objectid):
    """Display info about the object."""
    from ..utils import get_workflow_info
    from invenio_ext.sqlalchemy import db
    from itertools import groupby

    bwobject = BibWorkflowObject.query.get_or_404(objectid)
    # FIXME(jacquerie): to be removed in workflows >= 2.0
    bwobject.data = bwobject.get_data()
    bwobject.extra_data = bwobject.get_extra_data()

    previous_object, next_object = get_previous_next_objects(
        session.get("holdingpen_current_ids"),
        objectid
    )
    formatted_data = bwobject.get_formatted_data()
    extracted_data = extract_data(bwobject)

    action_name = bwobject.get_action()
    if action_name:
        action = actions[action_name]
        rendered_actions = action().render(bwobject)
    else:
        rendered_actions = {}

    if bwobject.id_parent:
        history_objects_db_request = BibWorkflowObject.query.filter(
            db.or_(BibWorkflowObject.id_parent == bwobject.id_parent,
                   BibWorkflowObject.id == bwobject.id_parent,
                   BibWorkflowObject.id == bwobject.id)).all()
    else:
        history_objects_db_request = BibWorkflowObject.query.filter(
            db.or_(BibWorkflowObject.id_parent == bwobject.id,
                   BibWorkflowObject.id == bwobject.id)).all()

    history_objects = {}
    temp = groupby(history_objects_db_request,
                   lambda x: x.version)
    for key, value in temp:
        if key != ObjectVersion.RUNNING:
            value = list(value)
            value.sort(key=lambda x: x.modified, reverse=True)
            history_objects[key] = value

    history_objects = sum(history_objects.values(), [])
    for obj in history_objects:
        obj._class = HOLDINGPEN_WORKFLOW_STATES[obj.version]["class"]
        obj.message = HOLDINGPEN_WORKFLOW_STATES[obj.version]["message"]
    results = get_rendered_task_results(bwobject)
    workflow_definition = get_workflow_info(extracted_data['workflow_func'])
    task_history = bwobject.get_extra_data().get('_task_history', [])
    return render_template(
        'workflows/details.html',
        bwobject=bwobject,
        rendered_actions=rendered_actions,
        history_objects=history_objects,
        bwparent=extracted_data['bwparent'],
        info=extracted_data['info'],
        log=extracted_data['logtext'],
        data_preview=formatted_data,
        workflow=extracted_data['w_metadata'],
        task_results=results,
        previous_object=previous_object,
        next_object=next_object,
        task_history=task_history,
        workflow_definition=workflow_definition,
        versions=ObjectVersion,
        pretty_date=pretty_date,
        workflow_class=workflows.get(extracted_data['w_metadata'].name),
    )
Beispiel #9
0
def render_page(path):
    """Internal interface to the page view."""
    page = Page.query.filter(db.or_(Page.url == request.path,
                                    Page.url == request.path + "/")).first()
    return render_template([page.template_name, cfg['PAGES_DEFAULT_TEMPLATE']],
                           page=page)