Beispiel #1
0
    def delete_from_json(cls, data):
        if isAllInData(['type', 'access_token'],
                       data) and data['type'] in cls.allowed_types:
            access_token = data['access_token']
            type = data['type']

            with DBConnection() as session:
                token = session.db.query(EntityToken).filter_by(
                    access_token=access_token, type=type).first()
                if token:
                    if type in cls.revoke_types:
                        with open("client_config.json") as client_config_file:
                            client_config = json.load(client_config_file)
                            client = client_config['clients'][type]
                        requests.post(client['revoke_token_url'],
                                      params={'token': access_token},
                                      headers={
                                          'content-type':
                                          'application/x-www-form-urlencoded'
                                      })

                    session.db.delete(token)
                    session.db.commit()

                    return {'token': access_token}, falcon.HTTP_200
                return {
                    'error': 'Invalid access token supplied'
                }, falcon.HTTP_400
        return {'error': 'Invalid parameters supplied'}, falcon.HTTP_400
Beispiel #2
0
    def update_from_query(cls, data):
        if isAllInData(['type', 'access_token'],
                       data) and data['type'] in cls.allowed_types:
            type = data['type']
            access_token = data['access_token']

            token = EntityToken.get().filter_by(access_token=access_token,
                                                type=type).first()
            if token:
                user = EntityUser.get().filter_by(eid=token.user_id).first()
                if user:

                    res_data, res_status = cls.get_info_api(access_token, type)
                    if res_status != falcon.HTTP_200:
                        with DBConnection() as session:
                            session.db.delete(token)
                            session.db.commit()
                        return res_data, res_status

                    EntityUser.update_user(token.user_id, res_data)

                    return token, user, None, falcon.HTTP_200
            return None, None, {
                'error': 'Invalid access token supplied'
            }, falcon.HTTP_400
        return None, None, {
            'error': 'Invalid parameters supplied'
        }, falcon.HTTP_400
Beispiel #3
0
    def update_from_json(cls, data):
        PROPNAME_MAPPING = EntityProp.map_name_id()
        eid = None
        PROP_MAPPING = {
            'image':
                lambda s, _eid, _id, _val: [PropMedia.delete(_eid, _id, False),
                                            PropMedia(_eid, _id,
                                                      cls.convert_media_value_to_media_item('image', _eid, _val)).
                                            add_or_update(session=s, no_commit=True)],
            'priority':
                lambda s, _eid, _id, _val: PropInt(eid, _id, _val).add_or_update(session=s, no_commit=True)
        }

        if 'id' in data:
            with DBConnection() as session:
                eid = data['id']
                entity = session.db.query(EntityNews).filter_by(eid=eid).all()
                fields = ['title', 'desc', 'text']
                if len(entity):
                    for _ in entity:
                        for l in cls.locales:
                            for f in fields:
                                if f in data and l in data[f]:
                                    setattr(_, '%s_%s' % (f, l), data[f][l])
                        session.db.commit()

                        if 'prop' in data:
                            for prop_name, prop_val in data['prop'].items():
                                if prop_name in PROPNAME_MAPPING and prop_name in PROP_MAPPING:
                                    PROP_MAPPING[prop_name](session, eid, PROPNAME_MAPPING[prop_name], prop_val)
                        session.db.commit()

        return eid
Beispiel #4
0
    def add(self):
        with DBConnection() as session:
            session.db.add(self)
            session.db.commit()
            return self.eid

        return None
 def delete(cls, eid, propid, raise_exception=True):
     with DBConnection() as session:
         res = session.db.query(cls).filter_by(eid=eid, propid=propid).all()
         if len(res):
             [[EntityScenario.delete(_.value), session.db.delete(_)] for _ in res]
             session.db.commit()
         elif raise_exception:
             raise FileNotFoundError('(eid, propid)=(%i, %i) was not found' % (eid, propid))
Beispiel #6
0
 def get_object_in_area(cls, propid, p, r):
     with DBConnection() as session:
         return [_[0] for _ in session.db.query(cls, EntityLocation)
             .filter(cls.propid == propid)
             .filter(EntityLocation.longitude.between(p[1] - r, p[1] + r))
             .filter(EntityLocation.latitude.between(p[0] - r, p[0] + r))
             .filter(cls.value == EntityLocation.eid)
             .all()]
Beispiel #7
0
 def get_object_property(cls, eid, propid):
     with DBConnection() as session:
         return [
             _[1].to_dict()
             for _ in session.db.query(cls, EntityLike).filter(
                 cls.eid == eid).filter(cls.propid == propid).filter(
                     cls.value == EntityLike.eid).all()
         ]
Beispiel #8
0
 def get_like_user_related(cls, eid, propid, userid):
     with DBConnection() as session:
         return [
             _[1].to_dict()
             for _ in session.db.query(cls, EntityLike).filter(
                 cls.eid == eid).filter(cls.propid == propid).filter(
                     cls.value == EntityLike.eid).filter(
                         EntityLike.userid == userid).all()
         ]
Beispiel #9
0
    def get(cls, session=None):
        def proceed(session):
            return session.db.query(cls)

        if session:
            return proceed(session)

        with DBConnection() as session:
            return proceed(session)
Beispiel #10
0
    def delete(cls, eid):
        with DBConnection() as session:
            res = session.db.query(cls).filter_by(eid=eid).all()

            if len(res):
                [session.db.delete(_) for _ in res]
                session.db.commit()
            else:
                raise FileNotFoundError('%s was not found' % cls.__name__)
Beispiel #11
0
    def delete_by_value(cls, eid, propid, value, raise_exception=True):
        with DBConnection() as session:
            res = session.db.query(cls).filter_by(eid=eid, propid=propid, value=value).all()

            if len(res):
                [session.db.delete(_) for _ in res]
                session.db.commit()
            else:
                if raise_exception:
                    raise FileNotFoundError('(eid, propid, value)=(%i, %i, %i) was not found' % (eid, propid, value))
    def delete(cls, eid):
        from each.Prop.PropLocation import PropLocation
        PropLocation.delete_value(eid, False)
        with DBConnection() as session:
            res = session.db.query(cls).filter_by(eid=eid).all()

            if len(res):
                [session.db.delete(_) for _ in res]
                session.db.commit()
            else:
                raise FileNotFoundError('%s was not found' % cls.__name__)
Beispiel #13
0
 def rating(_eid, propid):
     with DBConnection() as session:
         likes = session.db.query(PropLike, EntityLike). \
             filter(PropLike.eid == _eid). \
             filter(PropLike.propid == propid).filter(PropLike.value == EntityLike.eid).all()
         if len(likes):
             rate = 0
             for _ in likes:
                 rate += _[1].weight
             rate /= len(likes)
             return rate
     return 0
Beispiel #14
0
    def delete_value(cls, value, raise_exception=True):
        with DBConnection() as session:
            res = session.db.query(cls).filter_by(value=value).all()

            if len(res):
                EntityRun.delete(value)
                [session.db.delete(_) for _ in res]
                session.db.commit()
            else:
                if raise_exception:
                    raise FileNotFoundError('(value)=(%s) was not found' %
                                            str(value))
Beispiel #15
0
        def comment(_eid, propid):
            from each.Entities.EntityUser import EntityUser

            with DBConnection() as session:
                comments = session.db.query(EntityComment, EntityUser). \
                    join(EntityUser, EntityUser.eid == EntityComment.userid). \
                    filter(PropComment.eid == _eid). \
                    filter(PropComment.propid == propid). \
                    filter(EntityComment.eid == PropComment.value).order_by(EntityComment.created.desc()).all()
                if len(comments):
                    return [{'eid': _[0].eid, 'user': _[1].to_dict(['name', 'email']),
                            'comment': _[0].to_dict(['text', 'created'])} for _ in comments]
            return []
Beispiel #16
0
    def update_user(cls, eid, data):

        with DBConnection() as session:
            entity = session.db.query(EntityUser).filter_by(eid=eid).first()
            if entity:
                for _ in cls.required_fields:
                    if _ in data:
                        setattr(entity, _, data[_])

                ts = time.time()
                entity.updated = datetime.datetime.fromtimestamp(ts).strftime(
                    '%Y-%m-%d %H:%M')
                session.db.commit()
Beispiel #17
0
    def get_object_property(cls, eid, propid, session=None):
        def proceed(session):
            return [
                _interval_to_string(_.value)
                for _ in session.db.query(cls).filter_by(eid=eid,
                                                         propid=propid).all()
            ]

        if session:
            return proceed(session)

        with DBConnection() as session:
            return proceed(session)
Beispiel #18
0
    def delete(cls, eid):
        def safe_delete(item):
            if os.path.isfile(item.url):
                os.remove(item.url)
            session.db.delete(item)

        with DBConnection() as session:
            res = session.db.query(cls).filter_by(eid=eid).all()

            if len(res) == 1:
                [safe_delete(_) for _ in res]
                session.db.commit()
            else:
                raise FileNotFoundError('%s was not found' % cls.__name__)
Beispiel #19
0
    def update_from_json(cls, data):
        def mediaPropMapping(s, _eid, _id, _val):
            PropMedia.delete(_eid, _id, False)
            PropMedia(eid, _id, cls.convert_media_value_to_media_item('image', _eid, _val))\
                .add_or_update(session=s, no_commit=True)

        PROPNAME_MAPPING = EntityProp.map_name_id()

        eid = None

        PROP_MAPPING = {
            'logo':
            mediaPropMapping,
            'image':
            mediaPropMapping,
            'location':
            lambda s, _eid, _id, _val: [[
                PropLocation(_eid, _id, _).add(session=s, no_commit=True)
                for _ in _val['add']
            ],
                                        [
                                            PropLocation.delete_by_value(
                                                _eid, _id, _)
                                            for _ in _val['delete']
                                        ]]
        }

        if 'id' in data:
            with DBConnection() as session:
                eid = data['id']
                entity = session.db.query(EntityMuseum).filter_by(
                    eid=eid).all()
                fields = ['name', 'desc']
                if len(entity):
                    for _ in entity:
                        for l in cls.locales:
                            for f in fields:
                                if f in data and l in data[f]:
                                    setattr(_, '%s_%s' % (f, l), data[f][l])
                        session.db.commit()

                        if 'prop' in data:
                            for prop_name, prop_val in data['prop'].items():
                                if prop_name in PROPNAME_MAPPING and prop_name in PROP_MAPPING:
                                    PROP_MAPPING[prop_name](
                                        session, eid,
                                        PROPNAME_MAPPING[prop_name], prop_val)
                        session.db.commit()

        return eid
Beispiel #20
0
    def update(self, session, no_commit=False):
        def proseed(session):
            entities = self.__class__.get(session).filter_by(
                eid=self.eid, propid=self.propid).all()
            for _ in entities:
                _.value = self.value

            if not no_commit:
                session.db.commit()

        if session:
            return proseed(session)

        with DBConnection() as session:
            return proseed(session)
Beispiel #21
0
    def add(self, session=None, no_commit=False):
        def proseed(session):
            session.db.add(self)

            if not no_commit:
                session.db.commit()
                return self.eid

            return None

        if session:
            return proseed(session)

        with DBConnection() as session:
            return proseed(session)
Beispiel #22
0
def getTapeMuseums(**request_handler_args):
    req = request_handler_args['req']
    resp = request_handler_args['resp']

    first_m = getIntQueryParam('FirstMuseum', **request_handler_args)
    last_m = getIntQueryParam('LastMuseum', **request_handler_args)

    with DBConnection() as session:
        objects = session.db.query(EntityMuseum).order_by(
            EntityMuseum.created.desc()).all()

        count = objects.__len__()

    if first_m < 0:
        first_m = 0

    # if last_f isn't set (==-1), it is supposed to be an infinity
    if last_m == -1:
        museums = objects[first_m:]
    else:
        museums = objects[first_m:last_m + 1]

    if museums.__len__() == 0:
        if count > 0:
            if first_m > 0:
                first_m = min(int(first_m - math.fmod(first_m, 10)),
                              int(count - math.fmod(count, 10)))
            elif first_m < 0:
                first_m = 0
            museums = objects[first_m:first_m + 10]
        else:
            first_m = 0
    page = int((first_m - math.fmod(first_m, 10)) / 10) + 1

    res = []
    for _ in museums:
        obj_dict = _.to_dict(['eid', 'ownerid', 'name', 'desc'])
        wide_info = EntityMuseum.get_wide_object(
            _.eid, ['image', 'game', 'location', 'logo'])
        obj_dict.update(wide_info)
        res.append(obj_dict)

    res_dict = OrderedDict([('count', count), ('page', page), ('result', res)])

    resp.body = obj_to_json(res_dict)
    resp.status = falcon.HTTP_200
Beispiel #23
0
def getTapeFeeds(**request_handler_args):
    req = request_handler_args['req']
    resp = request_handler_args['resp']

    first_f = getIntQueryParam('FirstFeed', **request_handler_args)
    last_f = getIntQueryParam('LastFeed', **request_handler_args)

    with DBConnection() as session:
        objects = session.db.query(EntityNews, PropInt.value) \
            .join(PropInt, PropInt.eid == EntityNews.eid) \
            .order_by(PropInt.value.desc(), EntityNews.created.desc()).all()

        count = objects.__len__()

    if first_f < 0:
        first_f = 0

    # if last_f isn't set (==-1), it is supposed to be an infinity
    if last_f == -1:
        feeds = objects[first_f:]
    else:
        feeds = objects[first_f:last_f + 1]

    if feeds.__len__() == 0:
        if count > 0:
            if first_f > 0:
                first_f = min(int(first_f - math.fmod(first_f, 10)),
                              int(count - math.fmod(count, 10)))
            elif first_f < 0:
                first_f = 0
            feeds = objects[first_f:first_f + 10]
        else:
            first_f = 0
    page = int((first_f - math.fmod(first_f, 10)) / 10) + 1

    res = []
    for _ in feeds:
        obj_dict = _[0].to_dict(['eid', 'title', 'desc', 'text'])
        wide_info = EntityNews.get_wide_object(_[0].eid, ['image', 'priority'])
        obj_dict.update(wide_info)
        res.append(obj_dict)

    res_dict = OrderedDict([('count', count), ('page', page), ('result', res)])

    resp.body = obj_to_json(res_dict)
    resp.status = falcon.HTTP_200
Beispiel #24
0
    def add_from_json(cls, data):
        def mediaPropMapping(s, _eid, _id, _val, _uid):
            cls.process_media(s, 'image', _uid, _eid, _id, _val)

        PROPNAME_MAPPING = EntityProp.map_name_id()

        eid = None

        PROP_MAPPING = {
            'logo':
            mediaPropMapping,
            'image':
            mediaPropMapping,
            'location':
            lambda s, _eid, _id, _val, _uid: [
                PropLocation(_eid, _id, _).add(session=s, no_commit=True)
                for _ in _val['add']
            ]
        }

        if isAllInData(['name', 'desc', 'ownerid', 'prop'], data):
            create_args = {'ownerid': data['ownerid']}
            for _ in cls.locales:
                create_args['name_%s' %
                            _] = data['name'][_] if _ in data['name'] else ''
                create_args['desc_%s' %
                            _] = data['desc'][_] if _ in data['desc'] else ''
            new_entity = EntityMuseum(**create_args)
            eid = new_entity.add()

            with DBConnection() as session:
                for prop_name, prop_val in data['prop'].items():
                    if prop_name in PROPNAME_MAPPING and prop_name in PROP_MAPPING:
                        PROP_MAPPING[prop_name](session, eid,
                                                PROPNAME_MAPPING[prop_name],
                                                prop_val, eid)
                    else:
                        new_entity.delete(eid)
                        raise Exception(
                            '{%s} not existed property\nPlease use one of:\n%s'
                            % (prop_name, str(PROPNAME_MAPPING)))

                session.db.commit()

        return eid
Beispiel #25
0
def findLocationByName(**request_handler_args):
    req = request_handler_args['req']
    resp = request_handler_args['resp']

    start = getStringQueryParam("startswith", **request_handler_args)
    if start is None:
        resp.status = falcon.HTTP_400
        return
    with DBConnection() as session:
        objects = session.db.query(EntityLocation).filter(
            EntityLocation.name.startswith(start)).all()

    res = []
    for _ in objects:
        obj_dict = _.to_dict()
        res.append(obj_dict)

    resp.body = obj_to_json(res)
    resp.status = falcon.HTTP_200
Beispiel #26
0
def getTapeLocations(**request_handler_args):
    req = request_handler_args['req']
    resp = request_handler_args['resp']

    first_l = getIntQueryParam('FirstLocation', **request_handler_args)
    last_l = getIntQueryParam('LastLocation', **request_handler_args)

    with DBConnection() as session:
        objects = session.db.query(EntityLocation).order_by(
            EntityLocation.name).all()
        count = objects.__len__()

    if first_l < 0:
        first_l = 0

    # if last_f isn't set (==-1), it is supposed to be an infinity
    if last_l == -1:
        locations = objects[first_l:]
    else:
        locations = objects[first_l:last_l + 1]

    if locations.__len__() == 0:
        if count > 0:
            if first_l > 0:
                first_l = min(int(first_l - math.fmod(first_l, 10)),
                              int(count - math.fmod(count, 10)))
            elif first_l < 0:
                first_l = 0
            locations = objects[first_l:first_l + 10]
        else:
            first_l = 0
    page = int((first_l - math.fmod(first_l, 10)) / 10) + 1

    res = []
    for _ in locations:
        obj_dict = _.to_dict()
        res.append(obj_dict)

    res_dict = OrderedDict([('count', count), ('page', page), ('result', res)])

    resp.body = obj_to_json(res_dict)
    resp.status = falcon.HTTP_200
Beispiel #27
0
    def add_from_json(cls, data):
        from each.Prop.PropGame import PropGame
        PROPNAME_MAPPING = EntityProp.map_name_id()

        eid = None

        PROP_MAPPING = {
            'image':
                lambda s, _eid, _id, _val, _uid: cls.process_media(s, 'image', _uid, _eid, _id, _val),
            # in table - eid is museum id, and value is eid of game in each_game table
            'game':
                lambda s, _eid, _id, _val, _uid: PropGame(_val, _id, _eid).add(session=s, no_commit=True),
            'scenario':
                lambda s, _eid, _id, _val, _uid: PropScenario(_eid, _id, EntityScenario.add_by_game_id(_eid))
                                                    .add(session=s, no_commit=True)
        }

        if isAllInData(['name', 'desc', 'ownerid', 'active', 'prop'], data):
            create_args = {'ownerid': data['ownerid'], 'active': data['active']}
            for _ in cls.locales:
                create_args['name_%s' % _] = data['name'][_] if _ in data['name'] else ''
                create_args['desc_%s' % _] = data['desc'][_] if _ in data['desc'] else ''
            new_entity = EntityGame(**create_args)
            eid = new_entity.add()

            with DBConnection() as session:
                data['prop']['scenario'] = ''
                for prop_name, prop_val in data['prop'].items():
                    if prop_name in PROPNAME_MAPPING and prop_name in PROP_MAPPING:
                        PROP_MAPPING[prop_name](session, eid, PROPNAME_MAPPING[prop_name], prop_val, eid)
                    else:
                        new_entity.delete(eid)
                        raise Exception('{%s} not existed property\nPlease use one of:\n%s' %
                                        (prop_name, str(PROPNAME_MAPPING)))

                session.db.commit()

        return eid
Beispiel #28
0
    def add_from_json(cls, data):
        eid = None

        PROPNAME_MAPPING = EntityProp.map_name_id()

        PROP_MAPPING = {
            'image':
                lambda s, _eid, _id, _val, _uid: cls.process_media(s, 'image', _uid, _eid, _id, _val),
            'priority':
                lambda s, _eid, _id, _val, _uid: PropInt(eid, _id, _val).add_or_update(session=s, no_commit=False)
        }
        if isAllInData(['title', 'desc', 'text', 'prop'], data):
            create_args = {}
            if 'prop' in data:
                for _ in cls.locales:
                    create_args['title_%s' % _] = data['title'][_] if _ in data['title'] else ''
                    create_args['desc_%s' % _] = data['desc'][_] if _ in data['desc'] else ''
                    create_args['text_%s' % _] = data['text'][_] if _ in data['text'] else ''
            new_entity = EntityNews(**create_args)

            eid = new_entity.add()

            try:
                with DBConnection() as session:
                    for prop_name, prop_val in data['prop'].items():
                        if prop_name in PROPNAME_MAPPING and prop_name in PROP_MAPPING:
                            PROP_MAPPING[prop_name](session, eid, PROPNAME_MAPPING[prop_name], prop_val, eid)
                        else:
                            EntityNews.delete(eid)
                            raise Exception('{%s} not existed property\nPlease use one of:\n%s' %
                                        (prop_name, str(PROPNAME_MAPPING)))

                    session.db.commit()
            except Exception as e:
                EntityNews.delete(eid)
                raise Exception('Internal error')

        return eid
Beispiel #29
0
    def update_from_json(cls, data, prop):
        PROPNAME_MAPPING = EntityProp.map_name_id()

        eid = None

        if isAllInData(['userid', 'id'], data):
            userid = data['userid']
            _id = data['id']

            from each.Prop.PropLike import PropLike
            with DBConnection() as session:
                likes = session.db.query(PropLike, EntityLike).filter(PropLike.eid == _id).\
                    filter(PropLike.propid == PROPNAME_MAPPING[prop]).\
                    filter(PropLike.value == EntityLike.eid).filter(EntityLike.userid == userid).all()

                if len(likes):
                    eid = likes[0][0].value
                    if 'weight' in data:
                        for _ in likes:
                            setattr(_[1], 'weight', data['weight'])
                        session.db.commit()

        return eid
Beispiel #30
0
    def update_from_json(cls, data, prop):
        PROPNAME_MAPPING = EntityProp.map_name_id()

        eid = None

        if isAllInData(['userid', 'id'], data):
            userid = data['userid']
            _id = data['id']

            from each.Prop.PropComment import PropComment
            with DBConnection() as session:
                comments = session.db.query(PropComment, EntityComment).filter(PropComment.eid == _id). \
                    filter(PropComment.propid == PROPNAME_MAPPING[prop]). \
                    filter(PropComment.value == EntityComment.eid).filter(EntityComment.userid == userid).all()

                if len(comments):
                    eid = comments[0][0].value
                    if 'text' in data:
                        for _ in comments:
                            setattr(_[1], 'text', data['text'])
                        session.db.commit()

        return eid