kavanland
clone your own copy | download snapshot

Snapshots | iceberg

No images in this repository’s iceberg at this time

Inside this repository

views.py
text/x-python

Download raw (18.1 KB)

# This file is part of Active Archives.
# Copyright 2006-2011 the Active Archives contributors (see AUTHORS)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# Also add information on how to contact you by electronic and paper mail.


"""
Active Archives aacore views
"""

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.exceptions import PermissionDenied

from forms import ResourceForm, SparqlForm
from aacore.models import Namespace, Annotation
from aacore import app, NS
from urlparse import urlparse


import rdflib


#def cast(var):
    #try:
        #if int(var) == float(var):
            #return int(var)
    #except:
        #try:
            #return float(var)
        #except:
            #return var
#def cast(var): try: return float(var) except ValueError: return var


def work(request):
    #  print('you are looking at a work')

    ctx = {}

    return render(request, "aacore/work.html", ctx)


def books(request):
    #node = request.GET.get("http://purl.org/dc/terms/title")
    node = rdflib.URIRef("http://purl.org/dc/terms/title")

    as_predicate = app.graph.query("""
        SELECT DISTINCT ?subject ?object ?date
        WHERE {
            ?subject ?predicate ?object ;
            dcterms:title ?title.
            OPTIONAL { ?subject dcterms:issued ?date } .
            OPTIONAL { ?subject dcterms:date ?date }
        }
        GROUP BY ?subject
        ORDER BY DESC(?date) ?object
    """, initBindings={'predicate': node}, initNs=NS)

    ctx = {
        "node": node,
        "books": as_predicate,
    }
    return render(request, "aacore/books.html", ctx)


def browse2(request):
    node = request.GET.get("node")  # TODO: normalize trailing slash
    node = rdflib.URIRef(node)

    query = """
    SELECT DISTINCT ?kind
    WHERE {
        ?subject a ?kind .
    }
    """

    rows = app.graph.query(query, initBindings={'subject': node})
    kind = rows.bindings[0]['?kind'] if len(rows) else None

    if unicode(kind) == u"http://purl.org/vocab/frbr/core#Work":
        return work(request)

    elif unicode(kind) == u'http://xmlns.com/foaf/0.1/Document':
        return work(request)

    elif unicode(kind) == u'http://purl.org/vocab/bio/0.1/Death':
        return work(request)

    elif unicode(kind) == u'http://xmlns.com/foaf/0.1/Image':
        return work(request)

    elif unicode(kind) == u'http://purl.org/vocab/bio/0.1/Birth':
        return work(request)

    elif unicode(kind) == u'http://xmlns.com/foaf/0.1/Person':
        return work(request)

    ctx = {}

    return render(request, "aacore/browse2.html", ctx)


def browse(request):
    node = request.GET.get("node")  # TODO: normalize trailing slash
    #  import ipdb; ipdb.set_trace()

    # Homepage redirects to the page "http://kavan.land"
    if not node:
        node = "http://kavan.land/"
    do_reload = request.GET.get("_submit") == "reload"

    # If nothing is browsed, simply return an empty form
    if not node:
        form = ResourceForm()
        return render(request, "aacore/browse.html", {"form": form})
    else:
        if do_reload:
            app.index(node)

        annotation_list = Annotation.objects.filter(resource=node)

        # RDF distinguishes URI and literals...
        is_literal = urlparse(node).scheme not in ('file', 'http', 'https')

        if is_literal:
            node = rdflib.Literal(node)
        else:
            node = rdflib.URIRef(node)

        if "%s" % node == "sensational life+bio XXX":
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object1 .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }  {

                    {
                    ?subject ?predicate ?object2 .
                    FILTER (REGEX (?object2, "^bio ")).
                    }
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }
                }
                """, initBindings={'object1': "sensational life"} , initNs=NS)

        elif "%s" % node == "like XXX":
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object .
                    FILTER (REGEX (?object, "^like ")).
                    }
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                }
                """, initNs=NS)

        elif "%s" % node == "XXX likes":
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object .
                    FILTER (REGEX (?object, " likes$")).
                    }
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                }
                """, initNs=NS)

        elif "%s" % node == "web folklore|remix XXX":
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object1 .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    } UNION {

                    {
                    ?subject ?predicate ?object2 .
                    FILTER (REGEX (?object2, "^remix ")).
                    }
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }
                }
                """, initBindings={'object1': "web folklore"} , initNs=NS)

        elif "%s" % node == "active archives|papers XXX":
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object1 .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    } UNION  {

                    {
                    ?subject ?predicate ?object2 .
                    FILTER (REGEX (?object2, "^papers ")).
                    }
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }
                }
                """, initBindings={'object1': "active archives"} , initNs=NS)

        elif "%s" % node == "WW|WW 1|WW 2|war writer|war cold":
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object .
                    FILTER (REGEX (?object, "war|WW")).
                    }
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                }
                """, initNs=NS)


        elif "|" in node:
            nodes = node.split("|")
            #  print nodes

            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object1 .
                    OPTIONAL { ?subject dcterms:title ?title } .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dcterms:issued ?date } .
                    OPTIONAL { ?subject dcterms:date ?date }
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    } UNION {

                    ?subject ?predicate ?object2 .
                    OPTIONAL { ?subject dcterms:title ?title } .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dcterms:issued ?date } .
                    OPTIONAL { ?subject dcterms:date ?date }
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }
                }
                """, initBindings={'object1': nodes[0], 'object2': nodes[1]}, initNs=NS)

        elif "+" in node:
            nodes = node.split("+")
            #  print nodes

            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    {
                    ?subject ?predicate ?object1 .
                    OPTIONAL { ?subject dcterms:title ?title } .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dcterms:issued ?date } .
                    OPTIONAL { ?subject dcterms:date ?date }
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }  {

                    ?subject ?predicate ?object2 .
                    OPTIONAL { ?subject dcterms:title ?title } .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dcterms:issued ?date } .
                    OPTIONAL { ?subject dcterms:date ?date }
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                    }
                }
                """, initBindings={'object1': nodes[0], 'object2': nodes[1]}, initNs=NS)
        else:
            as_object = app.graph.query("""
                SELECT ?subject ?predicate  ?title ?date ?zItemType ?abstract
                WHERE {
                    ?subject ?predicate ?object .
                    OPTIONAL { ?subject dcterms:title ?title } .
                    OPTIONAL { ?subject dc:title ?title } .
                    OPTIONAL { ?subject dcterms:issued ?date } .
                    OPTIONAL { ?subject dcterms:date ?date }
                    OPTIONAL { ?subject dc:date ?date }
                    OPTIONAL { ?subject z:itemType ?zItemType } .
                    OPTIONAL { ?subject dcterms:abstract ?abstract }
                }
                GROUP BY ?subject
                """, initBindings={'object': node}, initNs=NS)
            #  for i in as_object:
            #      print(i)

        as_subject = app.graph.query("""
            SELECT ?predicate ?object
            WHERE {
                ?subject ?predicate ?object .
            }
            ORDER BY ?predicate
        """, initBindings={'subject': node})

        as_predicate = app.graph.query("""
            SELECT ?subject ?object
            WHERE {
                ?subject ?predicate ?object ;
                dcterms:title ?title.
                OPTIONAL { ?subject dcterms:issued ?date } .
                OPTIONAL { ?subject dcterms:date ?date }
            }
        """, initBindings={'predicate': node}, initNs=NS)


        kinds = app.graph.query("""
            SELECT DISTINCT ?type ?title
            WHERE {
                ?subject a ?type .
                OPTIONAL { ?subject dc:title ?title } .
                OPTIONAL { ?subject dcterms:title ?title } .
                OPTIONAL { ?subject purl:title ?title } .
            }""", initBindings={'subject': node}, initNs=NS)

        edition = app.graph.query("""
            SELECT DISTINCT ?workManifested ?title ?date
            WHERE {
                ?subject wemi:workManifested ?workManifested .
                OPTIONAL { ?subject purl:title ?title } .
                OPTIONAL { ?subject purl:date ?date . }
            }""", initNs=NS, initBindings={'subject': node})

        zItem = app.graph.query("""
            SELECT DISTINCT ?zItem
            WHERE {
                ?subject z:itemType ?zItem .
            }""", initNs=NS, initBindings={'subject': node})

        form = ResourceForm()

        ctx = {
            "node": node,
            "form": form,
            "as_subject": as_subject,
            "as_predicate": as_predicate,
            "as_object": as_object,
            "annotation_list": annotation_list,
            "kinds": kinds,
            "edition": edition,
            "zItem": zItem,
        }

        return render(request, "aacore/browse.html", ctx)


def browse3(request):
    node = request.GET.get("node")  # TODO: normalize trailing slash
    # RDF distinguishes URI and literals...
    is_literal = urlparse(node).scheme not in ('file', 'http', 'https')

    if is_literal:
        node = rdflib.Literal(node)
    else:
        node = rdflib.URIRef(node)

    as_object = app.graph.query("""SELECT ?subject ?predicate
        WHERE {
            ?subject ?predicate ?object .
        }
        """, initBindings={'object': node})

    as_subject = app.graph.query("""SELECT ?predicate ?object
        WHERE {
            ?subject ?predicate ?object .
        }
        """, initBindings={'subject': node})

    as_predicate = app.graph.query("""SELECT ?subject ?object
        WHERE {
            ?subject ?predicate ?object ;
        }
        """, initBindings={'predicate': node})

    ctx = {
        "as_subject": as_subject,
        "as_predicate": as_predicate,
        "as_object": as_object,
    }

    return render(request, "aacore/browse3.html", ctx)


def web_sparql(request):
    """
    Implement a simple browser-based SPARQL endpoint.

    Sends back Sparql results as an HTML table.
    """
    ctx = {}

    if request.method == 'POST': # If the form has been submitted...
        form = SparqlForm(request.POST) # A form bound to the POST data

        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            results = app.graph.query(form.cleaned_data['query'])
            ctx['results'] = results

    else:
        form = SparqlForm() # An unbound form

    ctx['form'] = form

    return render(request, 'aacore/sparql.html', ctx)


@csrf_exempt
@require_http_methods(["POST"])
def sparql(request):
    """
    Implement a simple SPARQL endpoint, accessible through POST requests.

    > Protocol clients may send protocol requests via the HTTP POST method
    > by including the query directly and unencoded as the HTTP request
    > message body. [1]

    Sends back Sparql results in an XML serialisation,
    with mime/type application/sparql-results+xml [2]

    If Accept HTTP header is set, sends back results in JSON with mime/type
    "application/sparql-results+json". For example, with CURL:

        curl \
        -i \
        -H "Content-Type: application/sparql-query" \
        -H "Accept: application/sparql-result+json" \
        -X POST \
        -d "SELECT ?s ?p ?o WHERE { ?s ?p ?o . }" \
        http://localhost:8000/sparql/

    [1] http://www.w3.org/TR/sparql11-protocol/#query-via-post-direct
    [2] http://www.w3.org/TR/rdf-sparql-XMLres/#mime
    """

    if request.META['CONTENT_TYPE'] == 'application/sparql-query':
        result = app.graph.query(request.body)

        if request.META.get('HTTP_ACCEPT') == "application/sparql-result+json":
            return HttpResponse(result.serialize(format='json'), mimetype="application/sparql-results+json")
        else:
            return HttpResponse(result.serialize(format='xml'), mimetype="application/sparql-results+xml")
    else:
        raise PermissionDenied


def namespaces_css(request):
    """
    Generates a stylesheet with the namespace colors.

    **Context**

    ``RequestContext``

    ``namespaces``
        A queryset of all :model:`aacore.Namespace`.

    **Template:**

    :template:`aacore/namespaces.css`
    """
    context = {}
    context['namespaces'] = Namespace.objects.all()
    return render(request, "aacore/namespaces.css", context=context, content_type="text/css")