Beispiel #1
0
def map_view(request, mapid, snapshot=None, template='maps/map_view.html'):
    """
    The view that returns the map composer opened to
    the map with the given map ID.
    """
    # ubah
    if (request.resolver_match.namespace == 'v2'): template = 'v2/map_view.html'
    # /ubah

    map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)
    if request.user != map_obj.owner and not request.user.is_superuser:
        Map.objects.filter(id=map_obj.id).update(popular_count=F('popular_count') + 1)
        queryset = matrix(user=request.user,resourceid=map_obj,action='View Geoexplorer')
        queryset.save()
    if snapshot is None:
        config = map_obj.viewer_json(request.user)
    else:
        config = snapshot_config(snapshot, map_obj, request.user)

    # translation for map legend
    # (map title, map abstract, layer title, layer abstract)
    if config['about']['title']:
        config['about']['title'] = _(config['about']['title'])
    if config['about']['abstract']:
        config['about']['abstract'] = _(config['about']['abstract'])
    for layer in config['map']['layers']:
        if 'title' in layer:
            if layer['title']:
                layer['title'] = _(layer['title'])
                if 'args' in layer:
                    for idx, val in enumerate(layer['args']):
                        if isinstance(val, list) == False and isinstance(val, dict) == False:
                            layer['args'][idx] = _(val)
        if 'capability' in layer:
            if 'abstract' in layer['capability']:
                if layer['capability']['abstract']:
                    layer['capability']['abstract'] = _(layer['capability']['abstract'])

        qs_orglogos = Layer.objects.filter(typename=layer['name'], orglogo__filename__isnull=False).values('orglogo__filename', 'orglogo__name')
        if qs_orglogos.count()>0:
            layer['attribution']='<img src="/static/v2/images/layer_logo/'+qs_orglogos[0]['orglogo__filename']+'" title="'+qs_orglogos[0]['orglogo__name']+'" alt="'+qs_orglogos[0]['orglogo__name']+'" height=50>'
        else:
            layer['attribution']=' '   
    # avatar_print_url_params = avatar_print_url(request.user, 200)
    # config['about']['print_org_logo'] = avatar_print_url_params['onpdf']
    # config['about']['org_logo'] = avatar_print_url_params['logo_url']
    # layernames = [l['name'] for l in config['map']['layers']]
    # qs_orglogos = Layer.objects.filter(typename__in=layernames, orglogo__filename__isnull=False).values('orglogo__filename').distinct()
    # orglogos = [l['orglogo__filename'] for l in qs_orglogos]

    return render_to_response(template, RequestContext(request, {
        'config': json.dumps(config),
        'map': map_obj
    }))
Beispiel #2
0
def document_download(request, docid):
    document = get_object_or_404(Document, pk=docid)
    if request.user != document.owner and not request.user.is_superuser:
        queryset = matrix(user=request.user,resourceid=document,action='Download')
        queryset.save()
    if not request.user.has_perm(
            'base.download_resourcebase',
            obj=document.get_self_resource()):
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to view this document.")})), status=401)
    return DownloadResponse(document.doc_file)
Beispiel #3
0
	def getRisk(self, request):

		p = urlparse(request.META.get('HTTP_REFERER')).path.split('/')
		mapCode = p[3] if 'v2' in p else p[2]
		map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)

		queryset = matrix(user=request.user,resourceid=map_obj,action='Interactive Calculation')
		queryset.save()

		requestbody = boundaryFilter = json.loads(request.body)

		wkts = ['ST_GeomFromText(\''+i+'\',4326)' for i in boundaryFilter['spatialfilter']]
		bring = wkts[-1] if len(wkts) else None
		filterLock = 'ST_Union(ARRAY['+', '.join(wkts)+'])'

		response = getSecurityStatistic(request, filterLock, boundaryFilter.get('flag'), boundaryFilter.get('code'), requestbody=requestbody)

		return response
Beispiel #4
0
def map_detail(request, mapid, snapshot=None, template='maps/map_detail.html'):
    '''
    The view that show details of each map
    '''
    # ubah
    if (request.resolver_match.namespace == 'v2'): template = 'v2/map_detail.html'
    # /ubah

    map_obj = _resolve_map(request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != map_obj.owner and not request.user.is_superuser:
        Map.objects.filter(id=map_obj.id).update(popular_count=F('popular_count') + 1)
        queryset = matrix(user=request.user,resourceid=map_obj,action='View')
        queryset.save()

    if snapshot is None:
        config = map_obj.viewer_json(request.user)
    else:
        config = snapshot_config(snapshot, map_obj, request.user)

    config = json.dumps(config)
    layers = MapLayer.objects.filter(map=map_obj.id)

    layernames = [l.name for l in layers]
    qs_orglogos = Layer.objects.filter(typename__in=layernames, orglogo__filename__isnull=False).values('orglogo__filename').distinct()
    orglogos = [l['orglogo__filename'] for l in qs_orglogos]

    context_dict = {
        "orglogos": orglogos,
        'config': config,
        'resource': map_obj,
        'layers': layers,
        'permissions_json': _perms_info_json(map_obj),
        "documents": get_related_documents(map_obj),
    }

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, map_obj)

    return render_to_response(template, RequestContext(request, context_dict))
Beispiel #5
0
def document_download(request, docid):
    document = get_object_or_404(Document, pk=docid)

    if request.user != document.owner and not request.user.is_superuser:
        queryset = matrix(user=request.user,
                          resourceid=document,
                          action='Download')
        queryset.save()

    if settings.MONITORING_ENABLED and document:
        if hasattr(document, 'alternate'):
            request.add_resource('document', document.alternate)

    if not request.user.has_perm('base.download_resourcebase',
                                 obj=document.get_self_resource()):
        return HttpResponse(loader.render_to_string(
            '401.html',
            context={
                'error_message':
                _("You are not allowed to view this document.")
            },
            request=request),
                            status=401)
    return DownloadResponse(document.doc_file)
Beispiel #6
0
def getOverviewMaps(request):
	selectedBox = request.GET['send']

	map_obj = _resolve_map(request, request.GET['mapID'], 'base.view_resourcebase', _PERMISSION_MSG_VIEW)
	queryset = matrix(user=request.user,resourceid=map_obj,action='Interactive Map Download')
	queryset.save()

	response = HttpResponse(content_type="image/png")
	url = 'http://asdc.immap.org/geoserver/geonode/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&LAYERS=geonode%3Aafg_admbnda_adm2%2Cgeonode%3Aafg_admbnda_adm1&STYLES=overview_adm2,overview_adm1&SRS=EPSG%3A4326&WIDTH=292&HEIGHT=221&BBOX=59.150390625%2C28.135986328125%2C76.025390625%2C38.792724609375'
	# url2='http://asdc.immap.org/geoserver/geonode/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&SRS=EPSG%3A4326&WIDTH=768&HEIGHT=485&BBOX=59.150390625%2C28.135986328125%2C76.025390625%2C38.792724609375&SLD_BODY='+selectedBox
	url2='http://asdc.immap.org/geoserver/geonode/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&SRS=EPSG%3A4326&WIDTH=292&HEIGHT=221&BBOX=59.150390625%2C28.135986328125%2C76.025390625%2C38.792724609375'
	template = '<sld:StyledLayerDescriptor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd" xmlns:sld="http://www.opengis.net/sld" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0">'
	template +='<sld:UserLayer>'
	template +=     '<sld:Name>Inline</sld:Name>'
	template +=      '<sld:InlineFeature>'
	template +=         '<sld:FeatureCollection>'
	template +=             '<gml:featureMember>'
	template +=                 '<feature>'
	template +=                     '<polygonProperty>'
	template +=                         '<gml:Polygon  srsName="4326">'
	template +=                             '<gml:outerBoundaryIs>'
	template +=                                 '<gml:LinearRing>'
	template +=                                     '<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">'+selectedBox
	template +=                                     '</gml:coordinates>'
	template +=                                 '</gml:LinearRing>'
	template +=                             '</gml:outerBoundaryIs>'
	template +=                         '</gml:Polygon>'
	template +=                      '</polygonProperty>'
	template +=                      '<title>Pacific NW</title>'
	template +=                 '</feature>'
	template +=             '</gml:featureMember>'
	template +=         '</sld:FeatureCollection>'
	template +=     '</sld:InlineFeature>'
	template +=     '<sld:UserStyle>'
	template +=         '<sld:FeatureTypeStyle>'
	template +=             '<sld:Rule>'
	template +=                 '<sld:PolygonSymbolizer>'
	template +=                     '<sld:Stroke>'
	template +=                         '<sld:CssParameter name="stroke">#FF0000</sld:CssParameter>'
	template +=                         '<sld:CssParameter name="stroke-width">1</sld:CssParameter>'
	template +=                     '</sld:Stroke>'
	template +=                 '</sld:PolygonSymbolizer>'
	template +=             '</sld:Rule>'
	template +=         '</sld:FeatureTypeStyle>'
	template +=     '</sld:UserStyle>'
	template += '</sld:UserLayer>'
	template +='</sld:StyledLayerDescriptor>'

	header = {
		"Content-Type": "application/json",
		"Authorization": "Basic " + base64.encodestring("boedy1996:kontol").replace('\n', '')
	}

	request1 = urllib2.Request(url, None, header)

	input_file = StringIO(urllib2.urlopen(request1).read())


	background = Image.open(input_file)

	values = {'SLD_BODY' : template}
	data = urllib.urlencode(values)


	request2 = urllib2.Request(url2, data)
	request2.add_header('Authorization', "Basic " + base64.encodestring("boedy1996:kontol").replace('\n', ''))
	response2 = urllib2.urlopen(request2)

	input_file2 = StringIO(response2.read())
	# input_file = StringIO(urllib2.urlopen(request2,data).read())

	overlay = Image.open(input_file2)

	new_img = Image.blend(background, overlay, 0.5)  #background.paste(overlay, overlay.size, overlay)

	new_img.save(response, 'PNG', quality=300)
	background.save(response, 'PNG', quality=300)

	return response
Beispiel #7
0
def document_detail(request, docid):
    """
    The view that show details of each document
    """
    document = None
    try:
        document = _resolve_document(
            request,
            docid,
            'base.view_resourcebase',
            _PERMISSION_MSG_VIEW)

    except Http404:
        return HttpResponse(
            loader.render_to_string(
                '404.html', RequestContext(
                    request, {
                        })), status=404)

    except PermissionDenied:
        return HttpResponse(
            loader.render_to_string(
                '401.html', RequestContext(
                    request, {
                        'error_message': _("You are not allowed to view this document.")})), status=403)

    if document is None:
        return HttpResponse(
            'An unknown error has occured.',
            mimetype="text/plain",
            status=401
        )

    else:
        try:
            related = document.content_type.get_object_for_this_type(
                id=document.object_id)
        except:
            related = ''

        # Update count for popularity ranking,
        # but do not includes admins or resource owners
        if request.user != document.owner and not request.user.is_superuser:
            Document.objects.filter(id=document.id).update(popular_count=F('popular_count') + 1)
            queryset = matrix(user=request.user,resourceid=document,action='View')
            queryset.save()

        metadata = document.link_set.metadata().filter(
            name__in=settings.DOWNLOAD_FORMATS_METADATA)
        preview_url = document.thumbnail_url.replace("-thumb", "-preview")
        context_dict = {
            'permissions_json': _perms_info_json(document),
            'resource': document,
            'metadata': metadata,
            'imgtypes': IMGTYPES,
            'related': related,
            'preview_url':preview_url}

        if settings.SOCIAL_ORIGINS:
            context_dict["social_links"] = build_social_links(request, document)

        # ubah
        template = 'documents/document_detail.html'
        if request.resolver_match.namespace == 'v2':
            template = 'v2/document_detail.html'
        return render_to_response(
            template,
            RequestContext(request, context_dict))
Beispiel #8
0
def common(request):
    response = {}
    code = None
    flag = 'entireAfg'
    filterLock = None
    rawFilterLock = None

    if 'page' not in request.GET:
        mutable = request.GET._mutable
        request.GET._mutable = True
        request.GET['page'] = 'baseline'
        request.GET._mutable = mutable

    if 'code' in request.GET:
        code = int(request.GET['code'])
        flag = 'currentProvince'

    if 'flag' in request.GET:
        filterLock = request.GET['filter']
        rawFilterLock = filterLock
        filterLock = 'ST_GeomFromText(\'' + filterLock + '\',4326)'
        flag = request.GET['flag']

    if 'pdf' in request.GET:
        # mapCode = '700'
        mapCode = settings.MATRIX_DEFAULT_MAP_CODE
        try:
            map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase',
                                   _PERMISSION_MSG_VIEW)
        except Exception as identifier:
            print 'Warning: _resolve_map() failed using settings.MATRIX_DEFAULT_MAP_CODE'
        else:
            px = get_object_or_404(Profile, id=request.GET['user'])
            queryset = matrix(user=px,
                              resourceid=map_obj,
                              action='Dashboard PDF ' + request.GET['page'])
            queryset.save()
    else:
        # mapCode = '700'
        mapCode = settings.MATRIX_DEFAULT_MAP_CODE
        try:
            map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase',
                                   _PERMISSION_MSG_VIEW)
        except Exception as identifier:
            print 'Warning: _resolve_map() failed using settings.MATRIX_DEFAULT_MAP_CODE.'
        else:
            queryset = matrix(user=request.user,
                              resourceid=map_obj,
                              action='Dashboard ' + request.GET['page'])
            queryset.save()

    page_name = request.GET['page']
    arg = [request, filterLock, flag, code]
    if page_name in ['accessibility', 'security']:
        arg = [request, rawFilterLock, flag, code]
    kwarg = {}
    page_name = 'avalancheforecast' if page_name == 'avalcheforecast' else page_name
    if page_name in ['drought']:
        if 'date' in request.GET:
            kwarg['date'] = request.GET.get('date')

    # get response data by importing module dynamically and run its dashboard functiion
    if page_name in settings.DASHBOARD_TO_APP.keys() \
    and settings.DASHBOARD_TO_APP[page_name] in settings.DASHBOARD_PAGE_MODULES:
        module = importlib.import_module(
            '%s.views' % (settings.DASHBOARD_TO_APP[page_name]))
        # page_meta = dict_ext(module.get_dashboard_meta()).pathget('pagenames', page_name)
        dashboard_meta = dict_ext(module.get_dashboard_meta())
        page_meta = list_ext([
            v for v in dashboard_meta.pathget('pages')
            if v.get('name') == page_name
        ]).get(0, dict_ext)
        response = dict_ext(
            page_meta.get('function')
            (*arg, **kwarg) if page_meta.get('function') else {})
        response['dashboard_template'] = page_meta.get('template')
    elif page_name == 'baseline':
        response = dashboard_baseline(*arg, **kwarg)
        response['dashboard_template'] = 'dash_baseline.html'
    elif page_name == 'main':
        response = getAllQuickOverview(*arg, **kwarg)
        response['dashboard_template'] = 'dash_main.html'
    else:
        raise Http404("Dashboard page '%s' not found" % (request.GET['page']))

    # if request.GET['page'] == 'baseline':
    # 	response = getBaseline(request, filterLock, flag, code)
    # elif request.GET['page'] == 'floodforecast':
    # 	response = getFloodForecast(request, filterLock, flag, code)
    # elif request.GET['page'] == 'floodrisk':
    # 	response = getFloodRisk(request, filterLock, flag, code)
    # elif request.GET['page'] == 'avalancherisk':
    # 	response = getAvalancheRisk(request, filterLock, flag, code)
    # elif request.GET['page'] == 'avalcheforecast':
    # 	response = getAvalancheForecast(request, filterLock, flag, code)
    # elif request.GET['page'] == 'accessibility':
    # 	response = getAccessibility(request, rawFilterLock, flag, code)
    # elif request.GET['page'] == 'earthquake':
    # 	response = getEarthquake(request, filterLock, flag, code)
    # elif request.GET['page'] == 'security':
    # 	response = getSecurity(request, rawFilterLock, flag, code)
    # elif request.GET['page'] == 'landslide':
    # 	response = getLandslideRisk(request, filterLock, flag, code)
    # elif request.GET['page'] == 'main':
    # 	response = getQuickOverview(request, filterLock, flag, code)

    response['add_link'] = '&code=' + str(
        code) if 'code' in request.GET else ''
    # if 'code' in request.GET:
    # 	response['add_link'] = '&code='+str(code)

    response['checked'] = request.GET['_checked'].split(
        ",") if '_checked' in request.GET else []
    # response['checked'] = []
    # if '_checked' in request.GET:
    # 	response['checked'] = request.GET['_checked'].split(",")

    response['jsondata'] = json.dumps(response, cls=JSONEncoderCustom)

    return response
Beispiel #9
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    # ubah
    if (request.resolver_match.namespace == 'v2'):
        template = 'v2/layer_detail.html'
    # /ubah

    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)
    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)
        queryset = matrix(user=request.user, resourceid=layer, action='View')
        queryset.save()

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    orglogos = [l.filename for l in layer.orglogo_set.all()]

    context_dict = {
        "orglogos": orglogos,
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')

    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links
        #added by razinal
        queryset = matrix(user=request.user,
                          resourceid=layer,
                          action='Download Layer')
        queryset.save()

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Beispiel #10
0
def common(request):
	response = {}
	code = None
	flag = 'entireAfg'
	filterLock = None
	rawFilterLock = None

	if 'page' not in request.GET:
		mutable = request.GET._mutable
		request.GET._mutable = True
		request.GET['page'] = 'baseline'
		request.GET._mutable = mutable

	if 'code' in request.GET:
		code = int(request.GET['code'])
		flag = 'currentProvince'

	if 'flag' in request.GET:
		filterLock = request.GET['filter']
		rawFilterLock = filterLock
		filterLock = 'ST_GeomFromText(\''+filterLock+'\',4326)'
		flag = request.GET['flag']

	if 'pdf' in request.GET:
		mapCode = '700'
		map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)
		px = get_object_or_404(Profile, id=request.GET['user'])
		# print px
		queryset = matrix(user=px,resourceid=map_obj,action='Dashboard PDF '+request.GET['page'])
		queryset.save()
	else:
		mapCode = '700'
		map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)
		queryset = matrix(user=request.user,resourceid=map_obj,action='Dashboard '+request.GET['page'])
		queryset.save()

	if request.GET['page'] == 'baseline':
		response = getBaseline(request, filterLock, flag, code)
	elif request.GET['page'] == 'floodforecast':
		response = getFloodForecast(request, filterLock, flag, code)
	elif request.GET['page'] == 'floodrisk':
		response = getFloodRisk(request, filterLock, flag, code)
	elif request.GET['page'] == 'avalancherisk':
		response = getAvalancheRisk(request, filterLock, flag, code)
	elif request.GET['page'] == 'avalcheforecast':
		response = getAvalancheForecast(request, filterLock, flag, code)
	elif request.GET['page'] == 'accessibility':
		response = getAccessibility(request, rawFilterLock, flag, code)
	elif request.GET['page'] == 'earthquake':
		response = getEarthquake(request, filterLock, flag, code)
	elif request.GET['page'] == 'security':
		response = getSecurity(request, rawFilterLock, flag, code)
	elif request.GET['page'] == 'landslide':
		response = getLandslideRisk(request, filterLock, flag, code)
	elif request.GET['page'] == 'drought':
		dateIn_str = request.GET['date'] if ('date' in request.GET) else str(date.today())
		dateIn = dateIn_str.split('-')
		woy = dateIn[0] + '%03d' % date(int(dateIn[0]), int(dateIn[1]), int(dateIn[2])).isocalendar()[1]
		closest_woy = getClosestDroughtWOY(woy)

		if request.GET.get('woy'):
			closest_woy = request.GET.get('woy')

		response = getDroughtRisk(request, filterLock, flag, code, closest_woy)
	elif request.GET['page'] == 'main':
		response = getQuickOverview(request, filterLock, flag, code)

	if 'code' in request.GET:
		response['add_link'] = '&code='+str(code)

	if request.GET.get('templatevar'):
		response.update(json.loads(request.GET.get('templatevar')))

	response['checked'] = []
	if '_checked' in request.GET:
		response['checked'] = filter(None, request.GET['_checked'].split(","))

	class CustomEncoder(json.JSONEncoder):
	    def default(self, obj):
	        if obj.__class__.__name__  == "GeoValuesQuerySet":
	            return list(obj)
	        elif obj.__class__.__name__  == "date":
	            return obj.strftime("%Y-%m-%d")
	        elif obj.__class__.__name__  == "datetime":
	            return obj.strftime("%Y-%m-%d %H:%M:%S")
	        elif obj.__class__.__name__  == "Decimal":
	            return float(obj)
	        else:
	            print 'not converted to json:', obj.__class__.__name__
	            # return {} # convert un-json-able object to empty object
	            return 'not converted to json: %s' % (obj.__class__.__name__) # convert un-json-able object to empty object

	response['jsondata'] = json.dumps(response, cls = CustomEncoder)

	return response
Beispiel #11
0
def common(request):
    response = {}
    code = None
    flag = 'entireAfg'
    filterLock = None
    rawFilterLock = None

    if 'page' not in request.GET:
        mutable = request.GET._mutable
        request.GET._mutable = True
        request.GET['page'] = 'baseline'
        request.GET._mutable = mutable

    if 'code' in request.GET:
        code = int(request.GET['code'])
        flag = 'currentProvince'

    if 'flag' in request.GET:
        filterLock = request.GET['filter']
        rawFilterLock = filterLock
        filterLock = 'ST_GeomFromText(\'' + filterLock + '\',4326)'
        flag = request.GET['flag']

    if 'pdf' in request.GET:
        mapCode = '700'
        map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase',
                               _PERMISSION_MSG_VIEW)
        px = get_object_or_404(Profile, id=request.GET['user'])
        # print px
        queryset = matrix(user=px,
                          resourceid=map_obj,
                          action='Dashboard PDF ' + request.GET['page'])
        queryset.save()
    else:
        mapCode = '700'
        map_obj = _resolve_map(request, mapCode, 'base.view_resourcebase',
                               _PERMISSION_MSG_VIEW)
        queryset = matrix(user=request.user,
                          resourceid=map_obj,
                          action='Dashboard ' + request.GET['page'])
        queryset.save()

    if request.GET['page'] == 'baseline':
        response = getBaseline(request, filterLock, flag, code)
    elif request.GET['page'] == 'floodforecast':
        response = getFloodForecast(request, filterLock, flag, code)
    elif request.GET['page'] == 'floodrisk':
        response = getFloodRisk(request, filterLock, flag, code)
    elif request.GET['page'] == 'avalancherisk':
        response = getAvalancheRisk(request, filterLock, flag, code)
    elif request.GET['page'] == 'avalcheforecast':
        response = getAvalancheForecast(request, filterLock, flag, code)
    elif request.GET['page'] == 'accessibility':
        response = getAccessibility(request, rawFilterLock, flag, code)
    elif request.GET['page'] == 'earthquake':
        response = getEarthquake(request, filterLock, flag, code)
    elif request.GET['page'] == 'security':
        response = getSecurity(request, rawFilterLock, flag, code)
    elif request.GET['page'] == 'landslide':
        response = getLandslideRisk(request, filterLock, flag, code)
    elif request.GET['page'] == 'drought':
        dateIn_str = request.GET['date'] if ('date' in request.GET) else str(
            date.today())
        dateIn = dateIn_str.split('-')
        woy = dateIn[0] + '%03d' % date(int(dateIn[0]), int(dateIn[1]),
                                        int(dateIn[2])).isocalendar()[1]
        closest_woy = getClosestDroughtWOY(woy)
        response = getDroughtRisk(request, filterLock, flag, code, closest_woy)
    elif request.GET['page'] == 'main':
        response = getQuickOverview(request, filterLock, flag, code)

    if 'code' in request.GET:
        response['add_link'] = '&code=' + str(code)

    response['checked'] = []
    if '_checked' in request.GET:
        response['checked'] = request.GET['_checked'].split(",")

    class CustomEncoder(json.JSONEncoder):
        def default(self, obj):
            if obj.__class__.__name__ == "GeoValuesQuerySet":
                return list(obj)
            elif obj.__class__.__name__ == "date":
                return obj.strftime("%Y-%m-%d")
            elif obj.__class__.__name__ == "datetime":
                return obj.strftime("%Y-%m-%d %H:%M:%S")
            elif obj.__class__.__name__ == "Decimal":
                return float(obj)
            else:
                print 'not converted to json:', obj.__class__.__name__
                # return {} # convert un-json-able object to empty object
                return 'not converted to json: %s' % (
                    obj.__class__.__name__
                )  # convert un-json-able object to empty object

    response['jsondata'] = json.dumps(response, cls=CustomEncoder)

    return response
Beispiel #12
0
def document_detail(request, docid):
    """
    The view that show details of each document
    """
    document = None
    try:
        document = _resolve_document(request, docid, 'base.view_resourcebase',
                                     _PERMISSION_MSG_VIEW)

    except Http404:
        return HttpResponse(loader.render_to_string('404.html',
                                                    context={},
                                                    request=request),
                            status=404)

    except PermissionDenied:
        return HttpResponse(loader.render_to_string(
            '401.html',
            context={
                'error_message':
                _("You are not allowed to view this document.")
            },
            request=request),
                            status=403)

    if document is None:
        return HttpResponse('An unknown error has occured.',
                            content_type="text/plain",
                            status=401)

    else:
        related = get_related_resources(document)

        # Update count for popularity ranking,
        # but do not includes admins or resource owners
        if request.user != document.owner and not request.user.is_superuser:
            Document.objects.filter(id=document.id).update(
                popular_count=F('popular_count') + 1)
            queryset = matrix(user=request.user,
                              resourceid=document,
                              action='View')
            queryset.save()

        metadata = document.link_set.metadata().filter(
            name__in=settings.DOWNLOAD_FORMATS_METADATA)
        preview_url = document.thumbnail_url.replace("-thumb", "-preview")

        group = None
        if document.group:
            try:
                group = GroupProfile.objects.get(slug=document.group.name)
            except GroupProfile.DoesNotExist:
                group = None
        context_dict = {
            'perms_list': get_perms(request.user,
                                    document.get_self_resource()),
            'permissions_json': _perms_info_json(document),
            'resource': document,
            'group': group,
            'metadata': metadata,
            'imgtypes': IMGTYPES,
            'related': related,
            'preview_url': preview_url
        }

        if settings.SOCIAL_ORIGINS:
            context_dict["social_links"] = build_social_links(
                request, document)

        if getattr(settings, 'EXIF_ENABLED', False):
            try:
                from geonode.contrib.exif.utils import exif_extract_dict
                exif = exif_extract_dict(document)
                if exif:
                    context_dict['exif_data'] = exif
            except BaseException:
                print "Exif extraction failed."

        return render(request,
                      "documents/document_detail.html",
                      context=context_dict)