Beispiel #1
0
def term_edit(uuid):
    msg = ''
    try:
        msg, term = Terms.get_term(uuid)
        # # print(term)
        if not term:
            raise Exception(msg)

        with vocabulary_editor_permission_factory({
                'name': term.vocabulary_id
        }).require():
            # # print(term.vocabulary_id)
            # user = current_user
            if not request.is_json:
                raise Exception("No JSON data provided")

            input_data = request.json
            # # print(input_data)
            msg, term = Terms.edit_term(uuid, input_data)
            if not term:
                raise Exception(msg)

            return iroko_json_response(
                IrokoResponseStatus.SUCCESS, \
                msg, 'term', \
                term_schema.dump(term)
                )
    except PermissionDenied as err:
        msg = 'Permission denied for editing term'
    except Exception as e:
        msg = str(e)

    return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #2
0
def term_delete(uuid):
    try:
        msg, term = Terms.get_term(uuid)
        with vocabulary_editor_permission_factory({
                'name': term.vocabulary_id
        }).require():
            msg, deleted = Terms.delete_term(uuid)
            if deleted:
                return iroko_json_response(IrokoResponseStatus.SUCCESS, msg,
                                           'term', {})
    except Exception as e:
        msg = str(e)
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #3
0
 def __init__(self, formdata=None, **kwargs):
     super(ProfileForm, self).__init__(formdata, **kwargs)
     if not current_userprofile.is_anonymous and current_userprofile_json_metadata:
         msg, institution = Terms.get_term_by_id(
             current_userprofile_json_metadata["institution_id"])
         if institution:
             self.institution.data = institution
Beispiel #4
0
def term_new():
    msg = ''
    try:
        # print(request)
        if not request.is_json:
            raise Exception("No JSON data provided")

        input_data = request.json

        with vocabulary_editor_permission_factory({
                'name':
                input_data['vocabulary_id']
        }).require():
            msg, term = Terms.new_term(input_data)
            if not term:
                raise Exception(msg)
            return iroko_json_response(
                IrokoResponseStatus.SUCCESS, \
                msg, 'term', \
                term_schema.dump(term)
                )

    except PermissionDenied as err:
        msg = 'Permission denied for adding term'
    except Exception as e:
        msg = str(e)
    return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #5
0
def term_get_tree(uuid):
    """Get a term given the uuid, in deep, meaning the children
    Receive <level> as an argument, defining the level of the tree considering the children as
    level=1 and parent as level=-1
    If argument <level> is not provided or equal 0, returns the first level, meaning only the term.
    Whith negative values it gets to the parents.
    TermNode
    {
        term:Term,
        children: TermNode[],
        parent:TermNode
    }
    """
    try:
        level = int(
            request.args.get('level')) if request.args.get('level') else 0
        msg, term = Terms.get_term(uuid)
        if not term:
            raise Exception(msg)

        return iroko_json_response(
            IrokoResponseStatus.SUCCESS, msg, 'term_node',
            term_node_schema.dump_term_node(term, level, 0))

    except Exception as e:
        msg = str(e)
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #6
0
def get_terms(vocabulary_id):
    """Get all terms of a vocabulary in a list """
    try:
        msg, terms = Terms.get_terms_by_vocab(vocabulary_id)
        return iroko_json_response(IrokoResponseStatus.SUCCESS, 'ok', 'terms',
                                   term_schema_many.dump(terms))
    except Exception as e:
        msg = str(e)
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #7
0
    def dump_term(self, termSource, **kwargs):
        # TODO: version_to_review is true cuando tiene una version con una fecha posterior a la
        #  version current.
        # # print("################################")
        # # print(termSource)
        # if termSource and 'term_id' in termSource:
        msg, term = Terms.get_term_by_id(termSource['term_id'])
        termSource['term'] = term_schema.dump(term)

        return termSource
Beispiel #8
0
def get_sources_by_term_statics(uuid):
    # TODO Mejorar esta api si se quiere que sea realmente generica
    # TODO verificar los tipos de soruces, pues luego si hay repositorios del MES o del uuid se
    #  contaran
    # esta api rest debe dar los tres ultimos ingresos
    # cant de revistas de ese termino
    # cant de instituciones
    # cant de records
    # uuid del MES: bb40299a-44bb-43be-a979-cd67dbb923d7

    try:
        ordered = False if request.args.get('ordered') and int(
            request.args.get('ordered')) == 0 else True
        status = request.args.get('status') if request.args.get(
            'status') else 'all'
        sources = SourcesDeprecated.get_all_sources_by_status(
            status=status, term_uuid=uuid, ordered_by_date=ordered)
        three = sources[0:3]
        msg, mes = Terms.get_term(uuid)
        institutions = []
        Terms.get_term_tree_list_by_level(mes, institutions, 1, 1)
        records = IrokoAggs.getAggrs("source.uuid", 50000)

        return iroko_json_response(
            IrokoResponseStatus.SUCCESS, \
            'ok', 'home_statics', \
            {
                'sources_count': len(sources),
                'last_sources': source_schema_many.dump(three),
                'institutions_count': len(institutions),
                'records': len(records)
                }
            )

        # last_approved = Sources.

    except Exception as e:
        return iroko_json_response(IrokoResponseStatus.ERROR, str(e), None,
                                   None)
Beispiel #9
0
def get_terms_list():
    """List all terms """
    try:
        result = Terms.get_terms()

        if not result:
            raise Exception('No terms found')

        return iroko_json_response(
            IrokoResponseStatus.SUCCESS, \
            'ok', 'terms', \
            term_schema_many.dump(result)
            )
    except Exception as e:
        msg = str(e)
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #10
0
def profile_form_factory():
    """Create a profile form."""
    t_biography = ''
    t_institution = 0
    t_institution_rol = ''
    t_avatar = ''
    if current_userprofile_json_metadata:
        t_biography = current_userprofile_json_metadata[
            "biography"] if "biography" in current_userprofile_json_metadata.keys(
            ) else ""
        msg, t_institution = Terms.get_term_by_id(
            current_userprofile_json_metadata["institution_id"]
        ) if "institution_id" in current_userprofile_json_metadata.keys(
        ) else 0
        t_institution_rol = current_userprofile_json_metadata[
            "institution_rol"] if "institution_rol" in current_userprofile_json_metadata.keys() \
            else ""
        t_avatar = current_userprofile_json_metadata[
            "avatar"] if "avatar" in current_userprofile_json_metadata.keys(
            ) else ""

    if current_app.config['USERPROFILES_EMAIL_ENABLED']:
        return EmailProfileForm(
            formdata=None,
            username=current_userprofile.username,
            full_name=current_userprofile.full_name,
            biography=t_biography,
            institution=t_institution.id if t_institution is not 0 else 0,
            avatar=base64.b64decode(str('t_avatar'))
            if t_avatar is not '' else None,
            email=current_user.email,
            email_repeat=current_user.email,
            prefix='profile',
        )
    else:

        return ProfileForm(
            formdata=None,
            username=current_userprofile.username,
            full_name=current_userprofile.full_name,
            biography=t_biography,
            institution=t_institution.id if t_institution is not 0 else 0,
            avatar=base64.b64decode(str('t_avatar'))
            if t_avatar is not '' else None,
            institution_rol=t_institution_rol,
            prefix='profile',
        )
Beispiel #11
0
def term_get_tree_by_id(id):
    """same as term_get_tree but receive id
    """
    try:
        level = int(
            request.args.get('level')) if request.args.get('level') else 0
        msg, term = Terms.get_term_by_id(id)
        if not term:
            raise Exception(msg)

        return iroko_json_response(
            IrokoResponseStatus.SUCCESS, msg, 'term_node',
            term_node_schema.dump_term_node(term, level, 0))

    except Exception as e:
        msg = str(e)
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #12
0
def get_term_in_list():
    try:
        ids = request.args.get('ids') if request.args.get('ids') else ''

        idsstr = ids.split(',')
        # print(ids)
        # print(idsstr)
        idlist = []
        for i in idsstr:
            idlist.append(int(i))

        terms = Terms.get_terms_by_id_list(idlist)
        if not terms:
            raise Exception('no terms in list')
        return iroko_json_response(IrokoResponseStatus.SUCCESS, 'ok', 'term',
                                   term_schema_many.dump(terms))
    except Exception as e:
        msg = str(e)
        return iroko_json_response(IrokoResponseStatus.ERROR, msg, None, None)
Beispiel #13
0
class ProfileForm(FlaskForm):
    """Form for editing user profile."""

    username = StringField(
        # NOTE: Form field label
        _('Username'),
        # NOTE: Form field help text
        description=_('Required. %(username_rules)s',
                      username_rules=USERNAME_RULES),
        validators=[DataRequired(message=_('Username not provided.'))],
        filters=[strip_filter],
    )

    full_name = StringField(
        # NOTE: Form label
        _('Full name'),
        filters=[strip_filter],
    )

    avatar = FileField(_('Avatar'),
                       description=_('An imagen for representing yourself'))

    biography = TextAreaField(
        _('Biography'),
        description=_('Short description of your biography'),
        validators=[validators.DataRequired()])

    institution = QuerySelectField(
        label=_('Institution'),
        query_factory=lambda: Terms.get_terms_by_vocabulary_name('institutions'
                                                                 ),
        widget=Select2Widget(),
        allow_blank=True,
        blank_text=_('Select Institution'))

    institution_rol = StringField(
        _('Role'),
        description=_('Role in the Institution'),
        filters=[strip_filter],
    )

    def validate_username(form, field):
        """Wrap username validator for WTForms."""
        try:
            validate_username(field.data)
        except ValueError as e:
            raise ValidationError(e)

        try:
            user_profile = UserProfile.get_by_username(field.data)
            if current_userprofile.is_anonymous or \
                (current_userprofile.user_id != user_profile.user_id and
                 field.data != current_userprofile.username):
                # NOTE: Form validation error.
                raise ValidationError(_('Username already exists.'))
        except NoResultFound:
            return

    def __init__(self, formdata=None, **kwargs):
        super(ProfileForm, self).__init__(formdata, **kwargs)
        if not current_userprofile.is_anonymous and current_userprofile_json_metadata:
            msg, institution = Terms.get_term_by_id(
                current_userprofile_json_metadata["institution_id"])
            if institution:
                self.institution.data = institution