Beispiel #1
0
    def wrapper(request, *args, **kwargs):
        timedata = datetime.now()
        data = func(request, timestamp=timedata, *args, **kwargs)
        logger.debug("Raw response data for %r: %r" % (func.__name__, data))
        response = HttpResponse()
        response["X-Weave-Timestamp"] = weave_timestamp(timedata)

        if settings.DEBUG and "debug" in request.GET:
            logger.debug("debug output for %r:" % func.__name__)

            if int(request.GET["debug"]) > 1:
                def load_payload(item):
                    if "payload" in item:
                        raw_payload = item["payload"]
                        payload_dict = json.loads(raw_payload)
                        item["payload"] = payload_dict
                    return item

                if isinstance(data, list):
                    data = [load_payload(item) for item in data]
                else:
                    data = load_payload(data)

            response["content-type"] = "text/plain"
            response.content = json.dumps(data, indent=4)
        else:
            if request.META.get("HTTP_ACCEPT") == 'application/newlines' and isinstance(data, list):
                response.content = '\n'.join([json.dumps(element) for element in data]) + '\n'
                response["content-type"] = 'application/newlines'
                response['X-Weave-Records'] = len(data)
            else:
                response["content-type"] = "application/json"
                response.content = json.dumps(data)

        return response
Beispiel #2
0
def info(request, version, username, timestamp):
    """
    return all collection keys with the timestamp
    https://wiki.mozilla.org/Labs/Weave/Sync/1.0/API#GET
    """
    collections = {}
    for collection in Collection.on_site.filter(user=request.user):
        collections[collection.name] = weave_timestamp(collection.modified)
    return collections
Beispiel #3
0
def info(request, version, username, timestamp):
    """
    return all collection keys with the timestamp
    https://wiki.mozilla.org/Labs/Weave/Sync/1.0/API#GET
    """
    collections = {}
    for collection in Collection.on_site.filter(user=request.user):
        collections[collection.name] = weave_timestamp(collection.modified)
    return collections
 def get_response_dict(self):
     response_dict = {
         "id": self.wboid,
         "modified": weave_timestamp(self.modified),
         "payload": self.payload,
     }
     # Don't send additional properties if payload is emtpy -> deleted Wbo
     if self.payload != '':
         for key in ("parentid", "predecessorid", "sortindex"):
             value = getattr(self, key)
             if value:
                 response_dict[key] = value
     return response_dict
Beispiel #5
0
 def get_response_dict(self):
     response_dict = {
         "id": self.wboid,
         "modified": weave_timestamp(self.modified),
         "payload": self.payload,
     }
     # Don't send additional properties if payload is emtpy -> deleted Wbo
     if self.payload != '':
         for key in ("parentid", "predecessorid", "sortindex"):
             value = getattr(self, key)
             if value:
                 response_dict[key] = value
     return response_dict
    def wrapper(request, *args, **kwargs):
        timedata = datetime.now()
        data = func(request, timestamp=timedata, *args, **kwargs)
        logger.debug("Raw response data for %r: %r" % (func.__name__, data))
        response = HttpResponse()
        response["X-Weave-Timestamp"] = weave_timestamp(timedata)

        if settings.DEBUG and "debug" in request.GET:
            logger.debug("debug output for %r:" % func.__name__)

            if int(request.GET["debug"]) > 1:

                def load_payload(item):
                    if "payload" in item:
                        raw_payload = item["payload"]
                        payload_dict = json.loads(raw_payload)
                        item["payload"] = payload_dict
                    return item

                if isinstance(data, list):
                    data = [load_payload(item) for item in data]
                else:
                    data = load_payload(data)

            response["content-type"] = "text/plain"
            response.content = json.dumps(data, indent=4)
        else:
            if request.META.get(
                    "HTTP_ACCEPT") == 'application/newlines' and isinstance(
                        data, list):
                response.content = '\n'.join(
                    [json.dumps(element) for element in data]) + '\n'
                response["content-type"] = 'application/newlines'
                response['X-Weave-Records'] = len(data)
            else:
                response["content-type"] = "application/json"
                response.content = json.dumps(data)

        return response
Beispiel #7
0
def storage(request, version, username, timestamp, col_name=None, wboid=None):
    """
    Handle storing Collections and WBOs. 
    """
    if 'X-If-Unmodified-Since' in request.META:
        since = datetime.fromtimestamp(float(request.META['X-If-Unmodified-Since']))
    else:
        since = None

    if request.method == 'GET':
        # Returns a list of the WBO contained in a collection.
        collection = get_object_or_404(Collection.on_site, user=request.user, name=col_name)

        if wboid is not None: # return one WBO
            wbo = get_object_or_404(Wbo, user=request.user, collection=collection, wboid=wboid)
            return wbo.get_response_dict()

        wbo_queryset = Wbo.objects.filter(user=request.user, collection=collection)
        wbo_queryset = limit_wbo_queryset(request, wbo_queryset)

        # If defined, returns the full WBO, rather than just the id. 
        if not 'full' in request.GET: # return only the WBO ids
            return [wbo.wboid for wbo in wbo_queryset]

        return [wbo.get_response_dict() for wbo in wbo_queryset]

    elif request.method == 'PUT':
        # https://wiki.mozilla.org/Labs/Weave/Sync/1.0/API#PUT
        # Adds the WBO defined in the request body to the collection.

        payload = request.raw_post_data
        logger.debug("Payload for PUT: %s" % payload)
        if not payload:
            raise NotImplementedError

        val = json.loads(payload)

        if val.get('id', None) != wboid:
            raise ValidationError

        # TODO: I don't think that it's good to just pass 0 in case the header is not defined
        collection, created = Collection.on_site.create_or_update(
                                                                  request.user,
                                                                  col_name,
                                                                  timestamp,
                                                                  since,
                                                                  )

        wbo, created = Wbo.objects.create_or_update(val, collection, request.user, timestamp)

        return weave_timestamp(timestamp)

    elif request.method == 'POST':
        status = {'success': [], 'failed': []}
        payload = request.raw_post_data
        logger.debug("Payload in POST: %s" % payload)
        if not payload:
            raise NotImplementedError

        # TODO: I don't think that it's good to just pass 0 in case the header is not defined
        collection, created = Collection.on_site.create_or_update(
                                                                  request.user,
                                                                  col_name,
                                                                  timestamp,
                                                                  since,
                                                                  )

        if created:
            logger.debug("Create new collection %s" % collection)
        else:
            logger.debug("Found existing collection %s" % collection)

        data = json.loads(payload)

        if not isinstance(data, list):
            raise NotImplementedError

        for item in data:
            try:
                wbo, created = Wbo.objects.create_or_update(item, collection, request.user, timestamp)
            except ValidationError, err:
                logger.debug("Can't create Wbo from %r: %s" % (item, err))
                status['failed'].append(item["id"])
            else:
                status['success'].append(wbo.wboid)

                if created:
                    logger.debug("New wbo created: %s" % wbo)
                else:
                    logger.debug("Existing wbo updated: %s" % wbo)

        return status
Beispiel #8
0
                logger.debug("Can't create Wbo from %r: %s" % (item, err))
                status['failed'].append(item["id"])
            else:
                status['success'].append(wbo.wboid)

                if created:
                    logger.debug("New wbo created: %s" % wbo)
                else:
                    logger.debug("Existing wbo updated: %s" % wbo)

        return status
    elif request.method == 'DELETE':
        # FIXME: This is am mess, it needs better structure
        if col_name is None and wboid is None:
            Collection.on_site.filter(user=request.user).delete()
            return weave_timestamp(timestamp)

        if col_name is not None and wboid is not None:
            try:
                wbo = Wbo.objects.get(user=request.user, collection__name=col_name, wboid=wboid)
            except Wbo.DoesNotExist, err:
                msg = (
                    "Deletion of wboid %s from collection %r for user %s requested,"
                    " but there is no such wbo: %s"
                ) % (wboid, col_name, request.user, err)
                logger.info(msg)
                if settings.DEBUG:
                    raise Http404(msg)
                else:
                    raise Http404()
            else:
Beispiel #9
0
def storage(request, version, username, timestamp, col_name=None, wboid=None):
    """
    Handle storing Collections and WBOs. 
    """
    if 'X-If-Unmodified-Since' in request.META:
        since = datetime.fromtimestamp(
            float(request.META['X-If-Unmodified-Since']))
    else:
        since = None

    if request.method == 'GET':
        # Returns a list of the WBO contained in a collection.
        collection = get_object_or_404(Collection.on_site,
                                       user=request.user,
                                       name=col_name)

        if wboid is not None:  # return one WBO
            wbo = get_object_or_404(Wbo,
                                    user=request.user,
                                    collection=collection,
                                    wboid=wboid)
            return wbo.get_response_dict()

        wbo_queryset = Wbo.objects.filter(user=request.user,
                                          collection=collection)
        wbo_queryset = limit_wbo_queryset(request, wbo_queryset)

        # If defined, returns the full WBO, rather than just the id.
        if not 'full' in request.GET:  # return only the WBO ids
            return [wbo.wboid for wbo in wbo_queryset]

        return [wbo.get_response_dict() for wbo in wbo_queryset]

    elif request.method == 'PUT':
        # https://wiki.mozilla.org/Labs/Weave/Sync/1.0/API#PUT
        # Adds the WBO defined in the request body to the collection.

        payload = request.raw_post_data
        logger.debug("Payload for PUT: %s" % payload)
        if not payload:
            raise NotImplementedError

        val = json.loads(payload)

        if val.get('id', None) != wboid:
            raise ValidationError

        # TODO: I don't think that it's good to just pass 0 in case the header is not defined
        collection, created = Collection.on_site.create_or_update(
            request.user,
            col_name,
            timestamp,
            since,
        )

        wbo, created = Wbo.objects.create_or_update(val, collection,
                                                    request.user, timestamp)

        return weave_timestamp(timestamp)

    elif request.method == 'POST':
        status = {'success': [], 'failed': []}
        payload = request.raw_post_data
        logger.debug("Payload in POST: %s" % payload)
        if not payload:
            raise NotImplementedError

        # TODO: I don't think that it's good to just pass 0 in case the header is not defined
        collection, created = Collection.on_site.create_or_update(
            request.user,
            col_name,
            timestamp,
            since,
        )

        if created:
            logger.debug("Create new collection %s" % collection)
        else:
            logger.debug("Found existing collection %s" % collection)

        data = json.loads(payload)

        if not isinstance(data, list):
            raise NotImplementedError

        for item in data:
            try:
                wbo, created = Wbo.objects.create_or_update(
                    item, collection, request.user, timestamp)
            except ValidationError, err:
                logger.debug("Can't create Wbo from %r: %s" % (item, err))
                status['failed'].append(item["id"])
            else:
                status['success'].append(wbo.wboid)

                if created:
                    logger.debug("New wbo created: %s" % wbo)
                else:
                    logger.debug("Existing wbo updated: %s" % wbo)

        return status
Beispiel #10
0
                logger.debug("Can't create Wbo from %r: %s" % (item, err))
                status['failed'].append(item["id"])
            else:
                status['success'].append(wbo.wboid)

                if created:
                    logger.debug("New wbo created: %s" % wbo)
                else:
                    logger.debug("Existing wbo updated: %s" % wbo)

        return status
    elif request.method == 'DELETE':
        # FIXME: This is am mess, it needs better structure
        if col_name is None and wboid is None:
            Collection.on_site.filter(user=request.user).delete()
            return weave_timestamp(timestamp)

        if col_name is not None and wboid is not None:
            try:
                wbo = Wbo.objects.get(user=request.user,
                                      collection__name=col_name,
                                      wboid=wboid)
            except Wbo.DoesNotExist, err:
                msg = (
                    "Deletion of wboid %s from collection %r for user %s requested,"
                    " but there is no such wbo: %s") % (wboid, col_name,
                                                        request.user, err)
                logger.info(msg)
                if settings.DEBUG:
                    raise Http404(msg)
                else: