Exemplo n.º 1
0
def create_group(request):
    try:
        variables = {'auth': request.authenticated_userid}

        req = request.json_body
        client = DBSession.query(Client).filter_by(id=variables['auth']).first()
        if not client:
            raise KeyError("Invalid client id (not registered on server). Try to logout and then login.",
                           variables['auth'])
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException("This client id is orphaned. Try to logout and then login once more.")
        if not DBSession.query(Group).filter_by(id=req['id']).first():
            group = Group(id=req['id'],
                             base_group_id=req['base_group_id'],
                             subject_client_id=req['subject_client_id'],
                             subject_object_id=req['subject_object_id'])
            DBSession.add(group)
            for user_id in req['users']:
                curr_user = DBSession.query(User).filter_by(id=user_id).first()
                if curr_user not in group.users:
                    group.users.append(curr_user)

        return {}
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}
Exemplo n.º 2
0
def create_lexical_entry_bulk(request):  # TODO: test
    try:
        dictionary_client_id = request.matchdict.get('dictionary_client_id')
        dictionary_object_id = request.matchdict.get('dictionary_object_id')
        perspective_client_id = request.matchdict.get('perspective_client_id')
        perspective_object_id = request.matchdict.get('perspective_object_id')

        count = request.json_body.get('count') or 0

        variables = {'auth': request.authenticated_userid}

        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login.",
                variables['auth'])
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )
        perspective = DBSession.query(DictionaryPerspective). \
            filter_by(client_id=perspective_client_id, object_id = perspective_object_id).first()
        if not perspective:
            request.response.status = HTTPNotFound.code
            return {'error': str("No such perspective in the system")}

        lexes_list = []
        for i in range(0, count):
            lexentr = LexicalEntry(client_id=variables['auth'],
                                   parent_object_id=perspective_object_id,
                                   parent=perspective)
            DBSession.add(lexentr)
            lexes_list.append(lexentr)
        DBSession.flush()
        lexes_ids_list = []
        for lexentr in lexes_list:
            lexes_ids_list.append({
                'client_id': lexentr.client_id,
                'object_id': lexentr.object_id
            })

        request.response.status = HTTPOk.code
        return lexes_ids_list
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 3
0
def create_translationgist(request):
    try:
        variables = {'auth': request.authenticated_userid}

        req = request.json_body
        object_id = req.get('object_id', None)
        type = req['type']
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login.",
                variables['auth'])
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )
        translationgist = TranslationGist(client_id=variables['auth'],
                                          object_id=object_id,
                                          type=type)
        DBSession.add(translationgist)
        DBSession.flush()
        basegroups = []
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can delete translationgist").first()
        ]
        if not object_id:
            groups = []
            for base in basegroups:
                group = Group(subject_client_id=translationgist.client_id,
                              subject_object_id=translationgist.object_id,
                              parent=base)
                groups += [group]
            for group in groups:
                add_user_to_group(user, group)
        request.response.status = HTTPOk.code
        return {
            'object_id': translationgist.object_id,
            'client_id': translationgist.client_id
        }
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 4
0
def create_organization(request):  # TODO: test
    try:

        variables = {'auth': request.authenticated_userid}
        req = request.json_body
        name = req['name']
        about = req['about']
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login."
            )
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )

        organization = Organization(name=name, about=about)
        if user not in organization.users:
            organization.users.append(user)
        DBSession.add(organization)
        DBSession.flush()
        bases = DBSession.query(BaseGroup).filter_by(subject='organization')
        for base in bases:
            group = Group(parent=base, subject_object_id=organization.id)
            add_user_to_group(user, group)
            DBSession.add(group)
        request.response.status = HTTPOk.code
        return {'organization_id': organization.id}
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 5
0
def create_persp_to_field(request):
    try:
        variables = {'auth': request.authenticated_userid}

        req = request.json_body
        client = DBSession.query(Client).filter_by(id=variables['auth']).first()
        if not client:
            raise KeyError("Invalid client id (not registered on server). Try to logout and then login.",
                           variables['auth'])
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException("This client id is orphaned. Try to logout and then login once more.")
        if not DBSession.query(DictionaryPerspectiveToField).filter_by(client_id=req['client_id'], object_id=req['object_id']).first():
            field_object = DictionaryPerspectiveToField(client_id=req['client_id'],
                                                        object_id=req['object_id'],
                                                        parent_client_id=req['parent_client_id'],
                                                        parent_object_id=req['parent_object_id'],
                                                        field_client_id=req['field_client_id'],
                                                        field_object_id=req['field_object_id'],
                                                        self_client_id=req['self_client_id'],
                                                        self_object_id=req['self_object_id'],
                                                        position=req['position'])
            DBSession.add(field_object)

        return {}
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 6
0
def create_language(request):  # tested & in docs
    try:
        variables = {'auth': request.authenticated_userid}

        req = request.json_body
        try:
            parent_client_id = req['parent_client_id']
            parent_object_id = req['parent_object_id']
        except:
            parent_client_id = None
            parent_object_id = None
        translation_gist_client_id = req['translation_gist_client_id']
        translation_gist_object_id = req['translation_gist_object_id']
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        object_id = req.get('object_id', None)
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login.",
                variables['auth'])
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )

        parent = None
        if parent_client_id and parent_object_id:
            parent = DBSession.query(Language).filter_by(
                client_id=parent_client_id,
                object_id=parent_object_id).first()
        language = Language(
            client_id=variables['auth'],
            object_id=object_id,
            translation_gist_client_id=translation_gist_client_id,
            translation_gist_object_id=translation_gist_object_id)
        DBSession.add(language)
        if parent:
            language.parent = parent
        DBSession.flush()
        basegroups = []
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can edit languages").first()
        ]
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can delete languages").first()
        ]
        if not object_id:
            groups = []
            for base in basegroups:
                group = Group(subject_client_id=language.client_id,
                              subject_object_id=language.object_id,
                              parent=base)
                groups += [group]
            for group in groups:
                add_user_to_group(user, group)
        request.response.status = HTTPOk.code
        return {
            'object_id': language.object_id,
            'client_id': language.client_id
        }
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 7
0
def convert_markup(request):
    import requests
    from lingvodoc.scripts.convert_rules import praat_to_elan
    try:
        variables = {'auth': request.authenticated_userid}
        req = request.json_body
        # out_type = req['out_type']
        client_id = req['client_id']
        object_id = req['object_id']

        l2e = DBSession.query(Entity).filter_by(client_id=client_id,
                                                object_id=object_id).first()
        # l2e = None
        if not l2e:
            raise KeyError("No such file")
        r = requests.get(l2e.content)
        if not r:
            raise CommonException("Cannot access file")
        content = r.content
        try:
            n = 10
            filename = time.ctime() + ''.join(
                random.SystemRandom().choice(string.ascii_uppercase +
                                             string.digits) for c in range(n))
            # extension = os.path.splitext(blob.content)[1]
            f = open(filename, 'wb')
        except Exception as e:
            request.response.status = HTTPInternalServerError.code
            return {'error': str(e)}
        try:
            f.write(content)
            f.close()
            if os.path.getsize(filename) / 1024 / 1024.0 < 1:
                if 'data_type' in l2e.additional_metadata:
                    if 'praat' in l2e.additional_metadata['data_type']:
                        content = praat_to_elan(filename)
                        if sys.getsizeof(content) / 1024 / 1024.0 < 1:
                            # filename2 = 'abc.xml'
                            # f2 = open(filename2, 'w')
                            # try:
                            #     f2.write(content)
                            #     f2.close()
                            #     # os.system('xmllint --noout --dtdvalid ' + filename2 + '> xmloutput 2>&1')
                            #     os.system('xmllint --dvalid ' + filename2 + '> xmloutput 2>&1')
                            # except:
                            #     print('fail with xmllint')
                            # finally:
                            #     pass
                            #     os.remove(filename2)
                            return content
                    elif 'elan' in l2e.additional_metadata['data_type']:
                        with open(filename, 'r') as f:
                            return f.read()
                    else:
                        raise KeyError("Not allowed convert option")
                    raise KeyError('File too big')
                raise KeyError("Not allowed convert option")
            raise KeyError('File too big')
        except Exception as e:
            request.response.status = HTTPInternalServerError.code
            return {'error': str(e)}
        finally:
            os.remove(filename)
            pass
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 8
0
def edit_organization(request):  # TODO: test
    try:
        response = dict()
        organization_id = request.matchdict.get('organization_id')
        organization = DBSession.query(Organization).filter_by(
            id=organization_id).first()

        variables = {'auth': request.authenticated_userid}
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login."
            )
        creator = DBSession.query(User).filter_by(id=client.user_id).first()
        if not creator:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )
        if organization:
            if not organization.marked_for_deletion:
                req = request.json_body
                if 'add_users' in req:
                    for user_id in req['add_users']:
                        user = DBSession.query(User).filter_by(
                            id=user_id).first()
                        if user not in organization.users:
                            if not user in organization.users:
                                organization.users.append(user)
                            bases = DBSession.query(BaseGroup).filter_by(
                                subject='organization')
                            for base in bases:
                                group = DBSession.query(Group).filter_by(
                                    base_group_id=base.id,
                                    subject_object_id=organization.id).first()
                                add_user_to_group(user, group)
                if 'delete_users' in req:
                    for user_id in req['delete_users']:
                        if user_id == creator.id:
                            raise CommonException(
                                "You shouldn't delete yourself")
                        user = DBSession.query(User).filter_by(
                            id=user_id).first()
                        if user in organization.users:
                            organization.users.remove(user)
                            bases = DBSession.query(BaseGroup).filter_by(
                                subject='organization')
                            for base in bases:
                                group = DBSession.query(Group).filter_by(
                                    base_group_id=base.id,
                                    subject_object_id=organization.id).first()
                                group.users.remove(user)
                if 'name' in req:
                    organization.name = req['name']
                if 'about' in req:
                    organization.about = req['about']
                request.response.status = HTTPOk.code
                return response

        request.response.status = HTTPNotFound.code
        return {'error': str("No such organization in the system")}
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}
Exemplo n.º 9
0
def signup_post(request):  # tested
    try:
        req = request.json_body
        login = req['login']
        name = req['name']
        email = req['email']
        password = req['password']

        day = req.get('day')
        month = req.get('month')
        year = req.get('year')
        if day is None or month is None or year is None:
            request.response.status = HTTPBadRequest.code
            return {'Error': "day, month or year of the birth is missing"}
        # birthday = datetime.datetime.strptime(day + month + year, "%d%m%Y").date()
        try:
            day = int(day)
            month = int(month)
            year = int(year)
            birthday = datetime.date(year, month, day)
        except ValueError:
            request.response.status = HTTPBadRequest.code
            return {'Error': "Invalid birthday"}

        if DBSession.query(User).filter_by(login=login).first():
            raise CommonException(
                "The user with this login is already registered")
        if DBSession.query(Email).filter_by(email=email).first():
            raise CommonException(
                "The user with this email is already registered")
        new_user = User(login=login,
                        name=name,
                        created_at=datetime.datetime.utcnow(),
                        intl_name=login,
                        birthday=birthday,
                        is_active=True)
        pwd = Passhash(password=password)
        email = Email(email=email)
        new_user.password = pwd
        new_user.email = email
        DBSession.add(new_user)
        basegroups = []
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can create dictionaries").first()
        ]
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can create languages").first()
        ]
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can create organizations").first()
        ]
        basegroups += [
            DBSession.query(BaseGroup).filter_by(
                name="Can create translation strings").first()
        ]
        groups = []
        for base in basegroups:
            groups += [
                DBSession.query(Group).filter_by(
                    subject_override=True, base_group_id=base.id).first()
            ]
        for group in groups:
            add_user_to_group(new_user, group)
        DBSession.flush()
        return {}

    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'status': request.response.status, 'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'status': request.response.status, 'error': str(e)}

    except ValueError as e:
        request.response.status = HTTPConflict.code
        return {'status': request.response.status, 'error': str(e)}
Exemplo n.º 10
0
def convert(request):  # TODO: test when convert in blobs will be needed
    import requests
    try:
        variables = {'auth': request.authenticated_userid}
        req = request.json_body
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login."
            )
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )
        out_type = req['out_type']
        client_id = req['client_id']
        object_id = req['object_id']

        blob = DBSession.query(UserBlobs).filter_by(
            client_id=client_id, object_id=object_id).first()
        if not blob:
            raise KeyError("No such file")
        r = requests.get(blob.content)
        if not r:
            raise CommonException("Cannot access file")
        content = r.content
        try:
            n = 10
            filename = time.ctime() + ''.join(
                random.SystemRandom().choice(string.ascii_uppercase +
                                             string.digits) for c in range(n))
            extension = os.path.splitext(blob.content)[1]
            f = open(filename + extension, 'wb')
        except Exception as e:
            request.response.status = HTTPInternalServerError.code
            return {'error': str(e)}
        try:
            f.write(content)
            f.close()
            data_type = blob.data_type
            for rule in rules:
                if data_type == rule.in_type and out_type == rule.out_type:
                    if extension in rule.in_extensions:
                        if os.path.getsize(
                                filename) / 1024 / 1024.0 < rule.max_in_size:
                            content = rule.convert(filename, req.get('config'),
                                                   rule.converter_config)
                            if sys.getsizeof(
                                    content
                            ) / 1024 / 1024.0 < rule.max_out_size:
                                request.response.status = HTTPOk.code
                                return {'content': content}
                    raise KeyError("Cannot access file")
        except Exception as e:
            request.response.status = HTTPInternalServerError.code
            return {'error': str(e)}
        finally:
            os.remove(filename)
            pass
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 11
0
def move_lexical_entry_bulk(request):
    req = request.json_body
    real_delete = req.get(
        'real_delete')  # With great power comes great responsibility
    # Maybe there needs to be check for permission of some sort (can really delete only when updating dictionary)
    variables = {'auth': request.authenticated_userid}
    client = DBSession.query(Client).filter_by(id=variables['auth']).first()
    if not client:
        raise KeyError(
            "Invalid client id (not registered on server). Try to logout and then login.",
            variables['auth'])
    user = DBSession.query(User).filter_by(id=client.user_id).first()
    if not user:
        raise CommonException(
            "This client id is orphaned. Try to logout and then login once more."
        )
    groups = DBSession.query(Group)\
        .join(BaseGroup, BaseGroup.id == Group.base_group_id)\
        .filter(BaseGroup.subject == 'lexical_entries_and_entities')\
        .filter(BaseGroup.action == 'create')\
        .join(User, Group.users)\
        .filter(User.id == user.id)\
        .group_by(Group)\
        .order_by('subject_override')\
        .all()

    wat = [o for o in groups]
    override = False
    ids = [{
        'client_id': o.subject_client_id,
        'object_id': o.subject_object_id
    } for o in groups]
    for group in groups:
        if group.subject_override:
            override = True
            break
    for par in req['move_list']:
        cli_id = par['client_id']
        obj_id = par['object_id']
        parent = DBSession.query(LexicalEntry).filter_by(
            client_id=cli_id, object_id=obj_id).first()
        can = True
        if parent:
            if not override:
                if {
                        'client_id': parent.parent_client_id,
                        'object_id': parent.parent_object_id
                } not in ids:
                    can = False
            if can:
                for ent in par['lexical_entries']:
                    can = True
                    object_id = ent['object_id']
                    client_id = ent['client_id']
                    entry = DBSession.query(LexicalEntry).filter_by(
                        client_id=client_id, object_id=object_id).first()
                    if entry:
                        if not override:
                            if {
                                    'client_id': entry.parent_client_id,
                                    'object_id': entry.parent_object_id
                            } not in ids:
                                can = False

                        if can:
                            if entry:
                                if parent.moved_to is None:
                                    if entry.moved_to is None:

                                        if not entry.marked_for_deletion and not parent.marked_for_deletion:
                                            # l1e = DBSession.query(LevelOneEntity).filter_by(parent = entry).all()
                                            l1e = list()
                                            for entity in l1e:
                                                # ent = DBSession.query(LevelOneEntity)\
                                                #     .filter_by(parent=parent,
                                                #                entity_type=entity.entity_type,
                                                #                content = entity.content)\
                                                #     .first()
                                                ent = None
                                                if ent:
                                                    entity.marked_for_deletion = True
                                                    if real_delete:
                                                        for publent in entity.publishleveloneentity:
                                                            DBSession.delete(
                                                                publent)
                                                        DBSession.delete(
                                                            entity)
                                                        continue
                                                entity.parent = parent

                                                for publent in entity.publishleveloneentity:
                                                    publent.marked_for_deletion = True
                                                    publent.parent = parent
                                                DBSession.flush()
                                            # ge = DBSession.query(GroupingEntity).filter_by(parent = entry).all()
                                            ge = list()
                                            for entity in ge:
                                                entity.parent = parent
                                                for publent in entity.publishgroupingentity:
                                                    publent.marked_for_deletion = True
                                                    publent.parent = parent
                                                DBSession.flush()
                                            entry.moved_to = str(
                                                cli_id) + '/' + str(obj_id)
                                            entry.marked_for_deletion = True
    request.response.status = HTTPOk.code
    return {}
Exemplo n.º 12
0
def move_lexical_entry(request):
    req = request.json_body
    variables = {'auth': request.authenticated_userid}
    client = DBSession.query(Client).filter_by(id=variables['auth']).first()
    if not client:
        raise KeyError(
            "Invalid client id (not registered on server). Try to logout and then login.",
            variables['auth'])
    user = DBSession.query(User).filter_by(id=client.user_id).first()
    if not user:
        raise CommonException(
            "This client id is orphaned. Try to logout and then login once more."
        )
    object_id = request.matchdict.get('object_id')
    client_id = request.matchdict.get('client_id')
    cli_id = req['client_id']
    obj_id = req['object_id']
    real_delete = req.get(
        'real_delete')  # With great power comes great responsibility
    # Maybe there needs to be check for permission of some sort (can really delete only when updating dictionary)
    entry = DBSession.query(LexicalEntry).filter_by(
        client_id=client_id, object_id=object_id).first()
    parent = DBSession.query(LexicalEntry).filter_by(client_id=cli_id,
                                                     object_id=obj_id).first()
    if entry and parent:
        groupoverride = DBSession.query(Group)\
            .filter_by(subject_override=True)\
            .join(BaseGroup)\
            .filter_by(subject='lexical_entries_and_entities')\
            .first()
        group = DBSession.query(Group)\
            .filter_by(subject_client_id=parent.parent_client_id, subject_object_id=parent.parent_object_id)\
            .join(BaseGroup)\
            .filter_by(subject='lexical_entries_and_entities')\
            .first()
        if user not in groupoverride.users and user not in group.users:
            raise CommonException(
                "You should only move to lexical entires you own")
        if parent.moved_to is None:
            if entry.moved_to is None:

                if not entry.marked_for_deletion and not parent.marked_for_deletion:
                    # l1e = DBSession.query(LevelOneEntity).filter_by(parent = entry).all()
                    l1e = list()
                    for entity in l1e:
                        # ent = DBSession.query(LevelOneEntity)\
                        #     .filter_by(parent=parent, entity_type=entity.entity_type, content = entity.content)\
                        #     .first()
                        ent = None
                        if ent:
                            entity.marked_for_deletion = True
                            if real_delete:
                                for publent in entity.publishleveloneentity:
                                    DBSession.delete(publent)
                                DBSession.delete(entity)
                                continue
                        entity.parent = parent

                        for publent in entity.publishleveloneentity:
                            publent.marked_for_deletion = True
                            publent.parent = parent
                        DBSession.flush()
                    # ge = DBSession.query(GroupingEntity).filter_by(parent = entry).all()
                    ge = list()
                    for entity in ge:
                        entity.parent = parent
                        for publent in entity.publishgroupingentity:
                            publent.marked_for_deletion = True
                            publent.parent = parent
                        DBSession.flush()
                    entry.moved_to = str(cli_id) + '/' + str(obj_id)
                    entry.marked_for_deletion = True
                    request.response.status = HTTPOk.code
                    return {}
    request.response.status = HTTPNotFound.code
    return {'error': str("No such lexical entry in the system")}
Exemplo n.º 13
0
def create_group_entity(request):  # tested
    try:
        variables = {'auth': authenticated_userid(request)}
        response = dict()
        req = request.json_body
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        object_id = req.get('object_id', None)
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login."
            )
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )
        tags = list()
        if 'tag' in req:
            tags.append(req['tag'])
        field_client_id = req['field_client_id']
        field_object_id = req['field_object_id']
        field = DBSession.query(Field).\
            filter_by(client_id=field_client_id, object_id=field_object_id).first()

        if not field:
            request.response.status = HTTPNotFound.code
            return {'error': str("No such field in the system")}
        if field.data_type != 'Grouping Tag':
            raise KeyError("wrong field data type")

        for par in req['connections']:
            parent = DBSession.query(LexicalEntry).\
                filter_by(client_id=par['client_id'], object_id=par['object_id']).first()
            if not parent:
                request.response.status = HTTPNotFound.code
                return {'error': str("No such lexical entry in the system")}
            par_tags = find_all_tags(parent, field_client_id, field_object_id)
            for tag in par_tags:
                if tag not in tags:
                    tags.append(tag)
        if not tags:
            n = 10  # better read from settings
            tag = time.ctime() + ''.join(
                random.SystemRandom().choice(string.ascii_uppercase +
                                             string.digits) for c in range(n))
            tags.append(tag)
        lexical_entries = find_lexical_entries_by_tags(tags, field_client_id,
                                                       field_object_id)
        for par in req['connections']:
            parent = DBSession.query(LexicalEntry).\
                filter_by(client_id=par['client_id'], object_id=par['object_id']).first()
            if parent not in lexical_entries:
                lexical_entries.append(parent)

        for lex in lexical_entries:
            for tag in tags:
                tag_entity = DBSession.query(Entity) \
                    .join(Entity.field) \
                    .filter(Entity.parent == lex,
                            Field.client_id == field_client_id,
                            Field.object_id == field_object_id,
                            Entity.content == tag).first()
                if not tag_entity:
                    tag_entity = Entity(client_id=client.id,
                                        object_id=object_id,
                                        field=field,
                                        content=tag,
                                        parent=lex)

                    group = DBSession.query(Group).join(BaseGroup).filter(
                        BaseGroup.subject == 'lexical_entries_and_entities',
                        Group.subject_client_id ==
                        tag_entity.parent.parent.client_id,
                        Group.subject_object_id ==
                        tag_entity.parent.parent.object_id,
                        BaseGroup.action == 'create').one()
                    if user in group.users:
                        tag_entity.publishingentity.accepted = True
        request.response.status = HTTPOk.code
        return response
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 14
0
def bulk_group_entities(request):  # tested
    try:
        variables = {'auth': authenticated_userid(request)}
        response = dict()
        req = request.json_body
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        field_client_id = req['field_client_id']
        field_object_id = req['field_object_id']
        counter = req['counter']
        field = DBSession.query(Field).\
            filter_by(client_id=field_client_id, object_id=field_object_id).first()

        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login."
            )
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )
        client.counter = counter
        DBSession.flush()
        if not field:
            request.response.status = HTTPNotFound
            return {'error': str("No such field in the system")}
        if field.data_type != 'Grouping Tag':
            raise KeyError("wrong field data type")

        for tag in req['tag_groups']:
            for tag_ent in req['tag_groups'][tag]:
                tag_entity = DBSession.query(Entity) \
                    .join(Entity.field) \
                    .filter(Entity.parent_client_id == tag_ent['parent_client_id'],
                            Entity.parent_object_id == tag_ent['parent_object_id'],
                            Field.client_id == tag_ent['field_client_id'],
                            Field.object_id == tag_ent['field_object_id'],
                            Entity.content == tag).first()
                if not tag_entity:
                    tag_entity = Entity(
                        client_id=client.id,
                        object_id=tag_ent['object_id'],
                        field=field,
                        content=tag_ent['content'],
                        parent_client_id=tag_ent['parent_client_id'],
                        parent_object_id=tag_ent['parent_object_id'])
                    lex = DBSession.query(LexicalEntry).filter_by(
                        client_id=tag_ent['parent_client_id'],
                        object_id=tag_ent['parent_object_id']).one()
                    group = DBSession.query(Group).join(BaseGroup).filter(
                        BaseGroup.subject == 'lexical_entries_and_entities',
                        Group.subject_client_id == lex.parent_client_id,
                        Group.subject_object_id == lex.parent_object_id,
                        BaseGroup.action == 'create').one()
                    if user in group.users:
                        tag_entity.publishingentity.accepted = True
        # if 'tag' in req:
        #     tags.append(req['tag'])

        for tag in req['tag_groups']:
            tags = list()
            tag_ent = req['tag_groups'][tag][0]
            parent = DBSession.query(LexicalEntry).\
                filter_by(client_id=tag_ent['parent_client_id'], object_id=tag_ent['parent_object_id']).first()
            if not parent:
                request.response.status = HTTPNotFound.code
                return {'error': str("No such lexical entry in the system")}
            par_tags = find_all_tags(parent, field_client_id, field_object_id)
            for tag in par_tags:
                if tag not in tags:
                    tags.append(tag)
            lexical_entries = find_lexical_entries_by_tags(
                tags, field_client_id, field_object_id)
            if parent not in lexical_entries:
                lexical_entries.append(parent)

            for lex in lexical_entries:
                for tag in tags:
                    tag_entity = DBSession.query(Entity) \
                        .join(Entity.field) \
                        .filter(Entity.parent == lex,
                                Field.client_id == field_client_id,
                                Field.object_id == field_object_id,
                                Entity.content == tag).first()
                    if not tag_entity:
                        tag_entity = Entity(client_id=client.id,
                                            field=field,
                                            content=tag,
                                            parent=lex)

                        group = DBSession.query(Group).join(BaseGroup).filter(
                            BaseGroup.subject ==
                            'lexical_entries_and_entities',
                            Group.subject_client_id == lex.parent_client_id,
                            Group.subject_object_id == lex.parent_object_id,
                            BaseGroup.action == 'create').one()
                        if user in group.users:
                            tag_entity.publishingentity.accepted = True
            request.response.status = HTTPOk.code
            response['counter'] = client.counter
            return response
    except KeyError as e:
        request.response.status = HTTPBadRequest.code
        return {'error': str(e)}

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}
Exemplo n.º 15
0
def create_entity(request):  # tested
    try:
        variables = {'auth': authenticated_userid(request)}
        response = dict()
        parent_client_id = request.matchdict.get('lexical_entry_client_id')
        parent_object_id = request.matchdict.get('lexical_entry_object_id')
        req = request.json_body
        client = DBSession.query(Client).filter_by(
            id=variables['auth']).first()
        object_id = req.get('object_id', None)
        if not client:
            raise KeyError(
                "Invalid client id (not registered on server). Try to logout and then login."
            )
        user = DBSession.query(User).filter_by(id=client.user_id).first()
        if not user:
            raise CommonException(
                "This client id is orphaned. Try to logout and then login once more."
            )

        parent = DBSession.query(LexicalEntry).filter_by(
            client_id=parent_client_id, object_id=parent_object_id).first()
        if not parent:
            request.response.status = HTTPNotFound.code
            return {'error': str("No such lexical entry in the system")}
        if 'content' not in req is None:
            request.response.status = HTTPBadRequest.code
            return {'error': 'Missing value: content'}
        additional_metadata = req.get('additional_metadata')
        upper_level = None
        # import pdb
        # pdb.set_trace(v
        # data_type = DBSession.query(TranslationAtom).filter(TranslationAtom.locale_id == 2).join(TranslationGist, and_(
        #     TranslationAtom.parent_client_id == TranslationGist.client_id,
        #     TranslationAtom.parent_object_id == TranslationGist.object_id)).join(Field, and_(
        #     TranslationGist.client_id == Field.data_type_translation_gist_client_id,
        #     TranslationGist.object_id == Field.data_type_translation_gist_object_id)).filter(
        #     Field.client_id == req['field_client_id'], Field.object_id == req['field_object_id']).first()
        tr_atom = DBSession.query(TranslationAtom).join(
            TranslationGist,
            and_(
                TranslationAtom.locale_id == 2,
                TranslationAtom.parent_client_id == TranslationGist.client_id,
                TranslationAtom.parent_object_id ==
                TranslationGist.object_id)).join(
                    Field,
                    and_(
                        TranslationGist.client_id ==
                        Field.data_type_translation_gist_client_id,
                        TranslationGist.object_id ==
                        Field.data_type_translation_gist_object_id)).filter(
                            Field.client_id == req['field_client_id'],
                            Field.object_id == req['field_object_id']).first()
        data_type = tr_atom.content.lower()
        if req.get('self_client_id') and req.get('self_object_id'):
            upper_level = DBSession.query(Entity).filter_by(
                client_id=req['self_client_id'],
                object_id=req['self_object_id']).first()
            if not upper_level:
                return {'error': str("No such upper level in the system")}
        entity = Entity(client_id=client.id,
                        object_id=object_id,
                        field_client_id=req['field_client_id'],
                        field_object_id=req['field_object_id'],
                        locale_id=req.get('locale_id'),
                        additional_metadata=additional_metadata,
                        parent=parent)
        group = DBSession.query(Group).join(BaseGroup).filter(
            BaseGroup.subject == 'lexical_entries_and_entities',
            Group.subject_client_id == entity.parent.parent.client_id,
            Group.subject_object_id == entity.parent.parent.object_id,
            BaseGroup.action == 'create').one()
        if user in group.users:
            entity.publishingentity.accepted = True
        if upper_level:
            entity.upper_level = upper_level
        filename = req.get('filename')
        real_location = None
        url = None
        if data_type == 'image' or data_type == 'sound' or 'markup' in data_type:
            real_location, url = create_object(request, req['content'], entity,
                                               data_type, filename)
            entity.content = url
            old_meta = entity.additional_metadata
            need_hash = True
            if old_meta:
                if old_meta.get('hash'):
                    need_hash = False
            if need_hash:
                hash = hashlib.sha224(base64.urlsafe_b64decode(
                    req['content'])).hexdigest()
                hash_dict = {'hash': hash}
                if old_meta:
                    old_meta.update(hash_dict)
                else:
                    old_meta = hash_dict
                entity.additional_metadata = old_meta
            if 'markup' in data_type:
                name = filename.split('.')
                ext = name[len(name) - 1]
                if ext.lower() == 'textgrid':
                    data_type = 'praat markup'
                elif ext.lower() == 'eaf':
                    data_type = 'elan markup'
            entity.additional_metadata['data_type'] = data_type
        elif data_type == 'link':
            try:
                entity.link_client_id = req['link_client_id']
                entity.link_object_id = req['link_object_id']
            except (KeyError, TypeError):
                request.response.status = HTTPBadRequest.code
                return {
                    'Error':
                    "The field is of link type. You should provide client_id and object id in the content"
                }
        else:
            entity.content = req['content']
        # return None
        DBSession.add(entity)
        request.response.status = HTTPOk.code
        response['client_id'] = entity.client_id
        response['object_id'] = entity.object_id
        return response

    except IntegrityError as e:
        request.response.status = HTTPInternalServerError.code
        return {'error': str(e)}

    except CommonException as e:
        request.response.status = HTTPConflict.code
        return {'error': str(e)}