Exemplo n.º 1
0
def exercise_image_upload(request):
    if request.method != 'POST':
        return HttpResponseBadRequest(
            "Only POST requests are allowed on this endpoint.")

    fobj = request.FILES.values()[0]
    name, ext = os.path.splitext(fobj._name)
    checksum = get_hash(DjFile(fobj))
    file_object = File(
        preset_id=format_presets.EXERCISE_IMAGE,
        file_on_disk=DjFile(request.FILES.values()[0]),
        file_format_id=ext[1:].lower(),
    )
    file_object.save()
    return HttpResponse(
        json.dumps({
            "success":
            True,
            "formatted_filename":
            exercises.CONTENT_STORAGE_FORMAT.format(str(file_object)),
            "file_id":
            file_object.pk,
            "path":
            generate_storage_url(str(file_object)),
        }))
Exemplo n.º 2
0
def generate_thumbnail(request):
    logging.debug("Entering the generate_thumbnail endpoint")

    if request.method != 'POST':
        return HttpResponseBadRequest(
            "Only POST requests are allowed on this endpoint.")
    else:
        data = json.loads(request.body)
        node = ContentNode.objects.get(pk=data["node_id"])

        thumbnail_object = generate_thumbnail_from_node(node)
        try:
            request.user.check_space(thumbnail_object.file_size,
                                     thumbnail_object.checksum)
        except Exception as e:
            if thumbnail_object:
                thumbnail_object.delete()
            raise e

        return HttpResponse(
            json.dumps({
                "success":
                True,
                "file":
                JSONRenderer().render(FileSerializer(thumbnail_object).data),
                "path":
                generate_storage_url(str(thumbnail_object)),
            }))
Exemplo n.º 3
0
def image_upload(request):
    # Used for content nodes
    if request.method != 'POST':
        return HttpResponseBadRequest("Only POST requests are allowed on this endpoint.")

    fobj = request.FILES.values()[0]
    name, ext = os.path.splitext(fobj._name)  # gets file extension without leading period
    checksum = get_hash(DjFile(fobj))
    request.user.check_space(fobj._size, checksum)

    file_object = File(
        contentnode_id=request.META.get('HTTP_NODE'),
        original_filename=name,
        preset_id=request.META.get('HTTP_PRESET'),
        file_on_disk=DjFile(request.FILES.values()[0]),
        file_format_id=ext[1:].lower(),
        uploaded_by=request.user
    )
    file_object.save()
    return HttpResponse(json.dumps({
        "success": True,
        "file": JSONRenderer().render(FileSerializer(file_object).data),
        "path": generate_storage_url(str(file_object)),
        "encoding": get_thumbnail_encoding(str(file_object)),
    }))
Exemplo n.º 4
0
def _write_user_row(file, writer, domain):
    if file.contentnode:
        channel = file.contentnode.get_channel()
        channel_name = channel.name if channel else _("No Channel")
        title = file.contentnode.title
        language = file.language.readable_name if file.language else file.contentnode.language.readable_name if file.contentnode.language else ""
        license = file.contentnode.license.license_name if file.contentnode.license else "No license"
        kind = next((k[1] for k in content_kinds.choices
                     if k[0] == file.contentnode.kind_id), None)
        description = file.contentnode.description
        author = file.contentnode.author
        license_description = file.contentnode.license_description
        copyright_holder = file.contentnode.copyright_holder

    else:
        title = _("No resource")
        channel_name = _("No Channel")
        kind = description = author = license = license_description = copyright_holder = ""
        language = file.language.readable_name if file.language else ""

    file_size = _format_size(file.file_size)
    url = "https://{}{}".format(domain, generate_storage_url(str(file)))

    writer.writerow([
        channel_name, title, kind, file.original_filename, file_size, url,
        description, author, language, license, license_description,
        copyright_holder
    ])
Exemplo n.º 5
0
def image_upload(request):
    if request.method != 'POST':
        return HttpResponseBadRequest(
            "Only POST requests are allowed on this endpoint.")

    fobj = request.FILES.values()[0]
    name, ext = os.path.splitext(
        fobj._name)  # gets file extension without leading period
    checksum = get_hash(DjFile(fobj))
    request.user.check_space(fobj._size, checksum)

    file_object = File(contentnode_id=request.META.get('HTTP_NODE'),
                       original_filename=name,
                       preset_id=request.META.get('HTTP_PRESET'),
                       file_on_disk=DjFile(request.FILES.values()[0]),
                       file_format_id=ext[1:].lower(),
                       uploaded_by=request.user)
    file_object.save()
    return HttpResponse(
        json.dumps({
            "success":
            True,
            "file":
            JSONRenderer().render(FileSerializer(file_object).data),
            "path":
            generate_storage_url(str(file_object)),
        }))
Exemplo n.º 6
0
def get_channel_thumbnail(channel):
    # Problems with json.loads, so use ast.literal_eval to get dict
    if channel.get("thumbnail_encoding"):
        thumbnail_data = ast.literal_eval(channel.get("thumbnail_encoding"))
        if thumbnail_data.get("base64"):
            return thumbnail_data["base64"]

    if channel.get("thumbnail"):
        return generate_storage_url(channel.get("thumbnail"))
Exemplo n.º 7
0
def image_upload(request):
    if request.method == 'POST':
        name, ext = os.path.splitext(request.FILES.values()[0]._name) # gets file extension without leading period
        file_object = File(contentnode_id=request.META.get('HTTP_NODE'),original_filename=name, preset_id=request.META.get('HTTP_PRESET'), file_on_disk=DjFile(request.FILES.values()[0]), file_format_id=ext[1:])
        file_object.save()
        return HttpResponse(json.dumps({
            "success": True,
            "file": JSONRenderer().render(FileSerializer(file_object).data),
            "path": generate_storage_url(str(file_object)),
        }))
Exemplo n.º 8
0
def exercise_image_upload(request):
    if request.method == 'POST':
        ext = os.path.splitext(request.FILES.values()[0]._name)[1][1:] # gets file extension without leading period
        file_object = File(preset_id=format_presets.EXERCISE_IMAGE, file_on_disk=DjFile(request.FILES.values()[0]), file_format_id=ext)
        file_object.save()
        return HttpResponse(json.dumps({
            "success": True,
            "formatted_filename": exercises.CONTENT_STORAGE_FORMAT.format(str(file_object)),
            "file_id": file_object.pk,
            "path": generate_storage_url(str(file_object)),
        }))
Exemplo n.º 9
0
    def retrieve_thumbail_src(self, node):
        """ Get either the encoding or the url to use as the <img> src attribute """
        try:
            if node.thumbnail_encoding:
                return json.loads(node.thumbnail_encoding).get('base64')
        except ValueError:
            pass

        thumbnail_file = node.files.filter(preset__thumbnail=True).first()
        if thumbnail_file:
            return generate_storage_url(str(thumbnail_file))
Exemplo n.º 10
0
def thumbnail_upload(request):
    if request.method == 'POST':
        fobj = request.FILES.values()[0]
        formatted_filename = write_file_to_storage(fobj)

        return HttpResponse(json.dumps({
            "success": True,
            "formatted_filename": formatted_filename,
            "file":  None,
            "path": generate_storage_url(formatted_filename),
        }))
    def test_get_node_thumbnail_file(self):
        new_node = ContentNode.objects.create(title="Heyo!", parent=self.channel.main_tree, kind=self.topic)
        thumbnail_file = create_thumbnail_from_base64(testdata.base64encoding())
        thumbnail_file.contentnode = new_node

        # we need to make sure the file is marked as a thumbnail
        preset, _created = FormatPreset.objects.get_or_create(id="video_thumbnail")
        preset.thumbnail = True
        thumbnail_file.preset = preset
        thumbnail_file.save()

        assert new_node.get_thumbnail() == generate_storage_url(str(thumbnail_file))
Exemplo n.º 12
0
def retrieve_thumbail_src(item):
    """ Get either the encoding or the url to use as the <img> src attribute """
    try:
        if item.get("thumbnail_encoding"):
            encoding = json.loads(item.get("thumbnail_encoding"))
            if encoding:
                return encoding.get("base64")
    except ValueError:
        pass
    if (item["thumbnail_checksum"] is not None
            and item["thumbnail_extension"] is not None):
        return generate_storage_url("{}.{}".format(
            item["thumbnail_checksum"], item["thumbnail_extension"]))
    return None
Exemplo n.º 13
0
    def test_get_node_thumbnail_file(self):
        new_node = ContentNode.objects.create(title="Heyo!",
                                              parent=self.channel.main_tree,
                                              kind=self.topic)
        thumbnail_file = create_thumbnail_from_base64(testdata.base64encoding())
        thumbnail_file.contentnode = new_node

        # we need to make sure the file is marked as a thumbnail
        preset, _created = FormatPreset.objects.get_or_create(id="video_thumbnail")
        preset.thumbnail = True
        thumbnail_file.preset = preset
        thumbnail_file.save()

        assert new_node.get_thumbnail() == generate_storage_url(str(thumbnail_file))
Exemplo n.º 14
0
def get_thumbnail(node):
    # Problems with json.loads, so use ast.literal_eval to get dict
    if node.thumbnail_encoding:
        thumbnail_data = ast.literal_eval(node.thumbnail_encoding)
        if thumbnail_data.get("base64"):
            return thumbnail_data["base64"]

    thumbnail = node.files.filter(preset__thumbnail=True).first()
    if thumbnail:
        return generate_storage_url(str(thumbnail))

    return "/".join([
        settings.STATIC_URL.rstrip("/"), "img",
        "{}_placeholder.png".format(node.kind_id)
    ])
Exemplo n.º 15
0
def thumbnail_upload(request):
    if request.method == 'POST':
        fobj = request.FILES.values()[0]
        checksum = get_hash(DjFile(fobj))
        request.user.check_space(fobj._size, checksum)

        formatted_filename = write_file_to_storage(fobj)

        return HttpResponse(
            json.dumps({
                "success": True,
                "formatted_filename": formatted_filename,
                "file": None,
                "path": generate_storage_url(formatted_filename),
            }))
Exemplo n.º 16
0
def _write_user_row(file, writer, domain):
    filename = '{}.{}'.format(file['checksum'], file['file_format__extension'])
    writer.writerow([
        file['channel_name'] or _("No Channel"),
        file['contentnode__title'] or _("No resource"),
        next((k[1] for k in content_kinds.choices if k[0] == file['contentnode__kind_id']), ''),
        file['original_filename'],
        _format_size(file['file_size'] or 0),
        generate_storage_url(filename),
        file['contentnode__description'],
        file['contentnode__author'],
        file['language__readable_name'] or file['contentnode__language__readable_name'],
        file['contentnode__license__license_name'],
        file['contentnode__license_description'],
        file['contentnode__copyright_holder'],
    ])
Exemplo n.º 17
0
def thumbnail_upload(request):
    # Used for channels
    if request.method != 'POST':
        return HttpResponseBadRequest("Only POST requests are allowed on this endpoint.")

    fobj = request.FILES.values()[0]
    checksum = get_hash(DjFile(fobj))
    request.user.check_space(fobj._size, checksum)

    formatted_filename = write_file_to_storage(fobj)

    return HttpResponse(json.dumps({
        "success": True,
        "formatted_filename": formatted_filename,
        "file": None,
        "path": generate_storage_url(formatted_filename),
        "encoding": get_thumbnail_encoding(formatted_filename),
    }))
Exemplo n.º 18
0
def thumbnail_upload(request):
    # Used for channels
    if request.method != 'POST':
        return HttpResponseBadRequest("Only POST requests are allowed on this endpoint.")

    fobj = request.FILES.values()[0]
    checksum = get_hash(DjFile(fobj))
    request.user.check_space(fobj._size, checksum)

    formatted_filename = write_file_to_storage(fobj)

    return HttpResponse(json.dumps({
        "success": True,
        "formatted_filename": formatted_filename,
        "file": None,
        "path": generate_storage_url(formatted_filename),
        "encoding": get_thumbnail_encoding(formatted_filename),
    }))
Exemplo n.º 19
0
def exercise_image_upload(request):
    if request.method != 'POST':
        return HttpResponseBadRequest("Only POST requests are allowed on this endpoint.")

    fobj = request.FILES.values()[0]
    assessment_item_id = request.POST.get('assessment_item_id', None)
    name, ext = os.path.splitext(fobj._name)
    get_hash(DjFile(fobj))
    file_object = File(
        preset_id=format_presets.EXERCISE_IMAGE,
        file_on_disk=DjFile(request.FILES.values()[0]),
        file_format_id=ext[1:].lower(),
        assessment_item_id=assessment_item_id,
    )
    file_object.save()
    return HttpResponse(json.dumps({
        "success": True,
        "formatted_filename": exercises.CONTENT_STORAGE_FORMAT.format(str(file_object)),
        "file_id": file_object.pk,
        "path": generate_storage_url(str(file_object)),
    }))
Exemplo n.º 20
0
def generate_thumbnail(request, contentnode_id):
    logging.debug("Entering the generate_thumbnail endpoint")

    if request.method != 'POST':
        return HttpResponseBadRequest("Only POST requests are allowed on this endpoint.")

    node = ContentNode.objects.get(pk=contentnode_id)

    thumbnail_object = generate_thumbnail_from_node(node)

    try:
        request.user.check_space(thumbnail_object.file_size, thumbnail_object.checksum)
    except Exception as e:
        if thumbnail_object:
            thumbnail_object.delete()
        raise e

    return HttpResponse(json.dumps({
        "success": True,
        "file": JSONRenderer().render(FileSerializer(thumbnail_object).data),
        "path": generate_storage_url(str(thumbnail_object)),
        "encoding": get_thumbnail_encoding(str(thumbnail_object)),
    }))
Exemplo n.º 21
0
def _write_user_row(file, writer, domain):
    if file.contentnode:
        channel = file.contentnode.get_channel()
        channel_name = channel.name if channel else _("No Channel")
        title = file.contentnode.title
        language = file.language.readable_name if file.language else file.contentnode.language.readable_name if file.contentnode.language else ""
        license = file.contentnode.license.license_name if file.contentnode.license else "No license"
        kind = next((k[1] for k in content_kinds.choices if k[0] == file.contentnode.kind_id), None)
        description = file.contentnode.description
        author = file.contentnode.author
        license_description = file.contentnode.license_description
        copyright_holder = file.contentnode.copyright_holder

    else:
        title = _("No resource")
        channel_name = _("No Channel")
        kind = description = author = license = license_description = copyright_holder = ""
        language = file.language.readable_name if file.language else ""

    file_size = _format_size(file.file_size)
    url = "https://{}{}".format(domain, generate_storage_url(str(file)))

    writer.writerow([channel_name, title, kind, file.original_filename, file_size, url,
                     description, author, language, license, license_description, copyright_holder])
Exemplo n.º 22
0
 def retrieve_storage_url(self, obj):
     return generate_storage_url(str(obj))
Exemplo n.º 23
0
    def test_get_channel_thumbnail_file(self):
        thumbnail_url = '/path/to/thumbnail.png'
        self.channel.thumbnail = thumbnail_url

        assert self.channel.get_thumbnail() == generate_storage_url(
            thumbnail_url)
    def test_get_channel_thumbnail_file(self):
        thumbnail_url = '/path/to/thumbnail.png'
        self.channel.thumbnail = thumbnail_url

        assert self.channel.get_thumbnail() == generate_storage_url(thumbnail_url)
Exemplo n.º 25
0
def retrieve_storage_url(item):
    """ Get the file_on_disk url """
    return generate_storage_url("{}.{}".format(item["checksum"],
                                               item["file_format"]))
Exemplo n.º 26
0
def get_thumbnail_url(item):
    return item.get("thumbnail") and generate_storage_url(item["thumbnail"])