Exemple #1
0
    def save_features(self):
        try:
            map_id = self.request.matchdict.get("map_id")
            map = DBSession.query(Map).get(map_id)
            if map is None:
                return HTTPNotFound()

            if not self.has_permission(self.request.user, map):
                return HTTPUnauthorized()

            if 'features' not in self.request.params:
                return HTTPBadRequest()

            features = self.request.params.get('features').\
                replace(u'\ufffd', '?')
            feature_collection = geojson.\
                loads(features, object_hook=geojson.GeoJSON.to_instance)

            for feature in feature_collection['features']:
                feature_id = feature.properties.get('fid')

                if feature_id:
                    cur_feature = DBSession.query(Feature).get(feature_id)
                    DBSession.delete(cur_feature)
                obj = Feature(feature)
                map.features.append(obj)

            DBSession.commit()
            return {'success': True}
        except:
            DBSession.rollback()
            traceback.print_exc(file=sys.stdout)
            return {'success': False}
Exemple #2
0
    def get_symbol(self):
        id = self.request.matchdict.get("symbol_id")
        try:
            symbol = DBSession.query(Symbols).\
                filter(Symbols.id == id).one()

            headers = {'Content-Type': 'application/octet-stream',
                       'Content-Disposition': 'filename=\"%s\";'
                       % (str(symbol.symbol_name))
                       }

            if symbol.symbol_name.lower().endswith(".jpg"):
                headers = {'Content-Type': 'image/jpeg'}
            if symbol.symbol_name.lower().endswith(".jpeg"):
                headers = {'Content-Type': 'image/jpeg'}
            if symbol.symbol_name.lower().endswith(".gif"):
                headers = {'Content-Type': 'image/gif'}
            if symbol.symbol_name.lower().endswith(".png"):
                headers = {'Content-Type': 'image/png'}
            return Response(symbol.symbol, headers=headers)

        except:
            from PIL import Image, ImageDraw
            from cStringIO import StringIO

            img = Image.new('RGBA', (40, 40))
            ImageDraw.Draw(img)

            buf = StringIO()
            img.save(buf, 'GIF', transparency=0)
            content = buf.getvalue()
            buf.close()
            headers = {'Content-Type': 'image/gif'}
            return Response(content, headers=headers)
Exemple #3
0
    def delete_all_features(self):
        id = self.request.matchdict.get("map_id")

        map = DBSession.query(Map).get(id)
        if map is None:
            return HTTPNotFound()
        if not self.has_permission(self.request.user, map):
            return HTTPUnauthorized()

        # remove the features associated to the map
        features = DBSession.query(Feature).filter(
            Feature.map_id == map.uuid).all()
        for f in features:
            DBSession.delete(f)
        DBSession.commit()
        return {'success': True}
Exemple #4
0
    def copy(self):
        id = self.request.matchdict.get("map_id")
        map = DBSession.query(Map).get(id)
        user = self.request.user
        if user is None:
            return HTTPUnauthorized()

        if map is None:
            return HTTPNotFound()

        DBSession.expunge(map)

        make_transient(map)
        map.uuid = None
        params = self.request.params
        if 'title' in params:
            map.title = unicode(params.get('title'))
        if 'description' in params:
            map.description = unicode(params.get('description'))
        map.public = False
        map.user_login = user.username
        map.category_id = None
        if 'category_id' in params:
            cat = params.get('category_id')
            map.category_id = None if cat == '' else cat
        if 'public' in params:
            str = unicode(params.get('public'))
            if str.lower() == u'true':
                map.public = True
        map.create_date = None
        map.update_date = None
        DBSession.add(map)
        DBSession.commit()

        if map.uuid is not None:
            features = DBSession.query(Feature).filter(
                Feature.map_id == id).all()
            for f in features:
                DBSession.expunge(f)
                make_transient(f)
                f.id = None
                map.features.append(f)
            DBSession.commit()

        return {'success': map.uuid is not None, 'uuid': map.uuid}
Exemple #5
0
    def delete_feature(self):
        id = self.request.matchdict.get("feature_id")

        feature = DBSession.query(Feature).get(id)
        if feature is None:
            return HTTPNotFound()

        map = DBSession.query(Map).get(feature.map_id)
        if map is None:
            return HTTPNotFound()

        if not self.has_permission(self.request.user, map):
            return HTTPUnauthorized()

        DBSession.delete(feature)
        DBSession.commit()

        return {'success': True}
Exemple #6
0
    def features(self):
        id = self.request.matchdict.get("map_id")
        map = DBSession.query(Map).get(id)
        if map is None:
            return HTTPNotFound()

        features = DBSession.query(Feature).filter(
            Feature.map_id == map.uuid).all()
        if 'cb' in self.request.params:
            headers = {'Content-Type': 'text/javascript; charset=utf-8'}
            return Response("%s(%s);"
                            % (self.request.params['cb'],
                               geojson.dumps(
                                   geojson.FeatureCollection(features))),
                            headers=headers)

        headers = {'Content-Type': 'application/json'}
        return Response(geojson.dumps(geojson.FeatureCollection(features)),
                        headers=headers)
Exemple #7
0
    def image(self):
        filename = self.request.matchdict.get("filename")
        if DBSession.query(Images).\
                filter(Images.name == filename).count() > 0:
            cur_file = DBSession.query(Images).\
                filter(Images.name == filename).one()
            the_image = cur_file.image
            if cur_file.name.lower().endswith(".jpg"):
                headers = {'Content-Type': 'image/jpeg'}
            if cur_file.name.lower().endswith(".jpeg"):
                headers = {'Content-Type': 'image/jpeg'}
            if cur_file.name.lower().endswith(".gif"):
                headers = {'Content-Type': 'image/gif'}
            if cur_file.name.lower().endswith(".png"):
                headers = {'Content-Type': 'image/png'}

            return Response(the_image, headers=headers)

        return HTTPNotFound()
Exemple #8
0
    def update(self):
        id = self.request.matchdict.get("map_id")
        map = DBSession.query(Map).get(id)

        if map is None:
            return HTTPNotFound()

        if not self.has_permission(self.request.user, map):
            return HTTPUnauthorized()

        return self.save(map, id)
Exemple #9
0
    def get_symbols(self):

        results = []
        try:
            symbol_type = self.request.params.get('symboltype', 'pixmap')
            if symbol_type == 'public':
                for symbol in DBSession.query(Symbols).\
                        filter(Symbols.is_public == True).all():  # noqa
                    results.append({'id': symbol.id,
                                    'name': symbol.symbol_name,
                                    'url': "/symbol/%s"
                                    % (str(symbol.id)),
                                    'symboltype': 'public'})

            if symbol_type == 'us':
                user = self.request.user
                if user is None:
                    return HTTPUnauthorized()
                for symbol in DBSession.query(Symbols).\
                        filter(Symbols.login_owner == user.username).all():
                    results.append({'id': symbol.id,
                                    'name': symbol.symbol_name,
                                    'url': "/symbol/%s"
                                    % (str(symbol.id)),
                                    'symboltype': 'us'})
        except:
            traceback.print_exc(file=sys.stdout)

        if 'cb' not in self.request.params:
            headers = {'Content-Type': 'application/json;charset=utf-8;'}
            return Response(json_dumps({'success': True,
                                        'count': len(results),
                                        'results': results}),
                            headers=headers)
        else:
            headers = {'Content-Type': 'text/javascript; charset=utf-8'}
            return Response((self.request.params['cb'] +
                             '(' + json_dumps({'success': True,
                                               'count': len(results),
                                               'results': results}) + ');'),
                            headers=headers)
Exemple #10
0
 def has_permission(self, user, map):
     if user is None:
         return False
     if map.user_login != user.username:
         user = self.request.user
         if user.is_admin is False:
             return False
         user_role = DBSession.query(Role).get(user.mymaps_role)
         if map.category is None or map.category.id not in\
                 [cat.id for cat in user_role.categories]:
             return False
     return True
Exemple #11
0
    def generate_symbol_file(self):

        user = self.request.user
        if user is None:
            return HTTPUnauthorized()

        dir = "/tmp/mapfile"
        if not os.path.exists(dir):
            os.mkdir(dir)
        symbolsmap = ""
        for symbol in DBSession.query(Symbols).all():
            _, ext = os.path.splitext(symbol.symbol_name)
            symbolsmap = symbolsmap + """
                SYMBOL
                      NAME "%s"
                      TYPE pixmap
                      IMAGE "/home/mapserver/config/MYMAPS/symbols/%s"
                END
            """ % (symbol.id, str(symbol.id) + ext)

        the_file = open(dir+"/symbols.map", 'w+')
        the_file.write(symbolsmap)
        the_file.close()
        os.system('sh ./scripts/sync_ms.sh %s' % (dir + "/" + "/symbols.map"))

        for symbol in DBSession.query(Symbols).\
                filter(Symbols.synchronized == False).all():  # noqa

            _, ext = os.path.splitext(symbol.symbol_name)

            the_name = str(symbol.id)+ext
            the_file = open(dir+"/"+the_name, 'w+')

            the_file.write(symbol.symbol)
            the_file.close()
            symbol.synchronized = True
            DBSession.commit()
            os.system('sh ./scripts/sync_ms.sh %s remove'
                      % (dir + "/" + the_name))
Exemple #12
0
    def map_info(self):
        id = self.request.matchdict.get("map_id")
        map = DBSession.query(Map).filter(Map.uuid == id).first()

        if map is None:
            return HTTPNotFound()
        if 'cb' in self.request.params:
            headers = {'Content-Type': 'text/javascript; charset=utf-8'}
            return Response("%s(%s);"
                            % (self.request.params['cb'],
                               json_dumps({'uuid': map.uuid,
                                           'title': map.title})),
                            headers=headers)
        else:
            headers = {'Content-Type': 'application/json'}
            return Response(json_dumps({'uuid': map.uuid, 'title': map.title}),
                            headers=headers)
Exemple #13
0
    def rate(self):
        id = self.request.matchdict.get("map_id")
        if 'rating' not in self.request.params:
            return HTTPBadRequest()
        rating = int(self.request.params.get('rating'))
        if rating < 0 or rating > 5:
            return HTTPBadRequest('Rating value should be between 0 and 5')

        map = DBSession.query(Map).get(id)
        if map is None:
            return HTTPBadRequest('Map does not exist')
        map.rating = ((map.rating * map.rating_count + rating) /
                      (map.rating_count + 1))
        map.rating_count = map.rating_count + 1
        try:
            DBSession.add(map)
            DBSession.commit()
            return {
                'success': True,
                'rating': map.rating,
                'rating_count': map.rating_count
            }
        except Exception:
            return {'success': False}