Пример #1
0
 def test_exportchannel_thumbnail(self):
     node = ContentNode(title="Test Node", kind_id=content_kinds.VIDEO)
     node.save()
     newfile = create_associated_thumbnail(node, self.thumbnail_fobj)
     self.assertTrue(isinstance(newfile, File))
     thumbnail_data = json.loads(node.thumbnail_encoding)
     self.assertEqual(thumbnail_data['base64'], generated_base64encoding())
Пример #2
0
 def test_exportchannel_thumbnail(self):
     node = ContentNode(title="Test Node", kind_id=content_kinds.VIDEO)
     node.save()
     newfile = create_associated_thumbnail(node, self.thumbnail_fobj)
     self.assertTrue(isinstance(newfile, File))
     thumbnail_data = json.loads(node.thumbnail_encoding)
     self.assertEqual(thumbnail_data['base64'], generated_base64encoding())
Пример #3
0
 def test_create_node_that_already_exists_no_integrity_error(self):
     obj = ContentNode.objects.first()
     new_obj = ContentNode(id=obj.id, kind_id=content_kinds.TOPIC)
     try:
         new_obj.save()
     except IntegrityError:
         self.fail("Caused an IntegrityError")
Пример #4
0
def file_create(request):
    if request.method == 'POST':
        original_filename, ext = os.path.splitext(
            request.FILES.values()[0]._name)
        size = request.FILES.values()[0]._size
        presets = FormatPreset.objects.filter(
            allowed_formats__extension__contains=ext[1:].lower())
        kind = presets.first().kind
        preferences = json.loads(request.user.preferences)
        author = preferences.get('author') or ""
        license = License.objects.filter(
            license_name=preferences.get('license')).first(
            )  # Use filter/first in case preference hasn't been set
        license_id = license.pk if license else settings.DEFAULT_LICENSE
        new_node = ContentNode(
            title=original_filename,
            kind=kind,
            license_id=license_id,
            author=author,
            copyright_holder=preferences.get('copyright_holder'))
        if license.license_name == licenses.SPECIAL_PERMISSIONS:
            new_node.license_description = preferences.get(
                'license_description')
        new_node.save()
        file_object = File(file_on_disk=DjFile(request.FILES.values()[0]),
                           file_format_id=ext[1:].lower(),
                           original_filename=request.FILES.values()[0]._name,
                           contentnode=new_node,
                           file_size=size)
        file_object.save()
        if kind.pk == content_kinds.VIDEO:
            file_object.preset_id = guess_video_preset_by_resolution(
                str(file_object.file_on_disk))
        elif presets.filter(supplementary=False).count() == 1:
            file_object.preset = presets.filter(supplementary=False).first()

        file_object.save()

        try:
            if preferences.get('auto_derive_video_thumbnail') and new_node.kind_id == content_kinds.VIDEO \
                or preferences.get('auto_derive_audio_thumbnail') and new_node.kind_id == content_kinds.AUDIO \
                or preferences.get('auto_derive_html5_thumbnail') and new_node.kind_id == content_kinds.HTML5 \
                or preferences.get('auto_derive_document_thumbnail') and new_node.kind_id == content_kinds.DOCUMENT:
                generate_thumbnail_from_node(new_node, set_node=True)
        except Exception:
            pass

        return HttpResponse(
            json.dumps({
                "success":
                True,
                "node":
                JSONRenderer().render(
                    ContentNodeEditSerializer(new_node).data)
            }))
Пример #5
0
def file_create(request):
    if request.method == 'POST':
        ext = os.path.splitext(request.FILES.values()[0]._name)[1].split(".")[-1]
        size = request.FILES.values()[0]._size
        kind = FormatPreset.objects.filter(allowed_formats__extension__contains=ext).first().kind
        original_filename = request.FILES.values()[0]._name
        new_node = ContentNode(title=original_filename.split(".")[0], kind=kind, license_id=settings.DEFAULT_LICENSE, author=request.user.get_full_name())
        new_node.save()
        file_object = File(file_on_disk=request.FILES.values()[0], file_format=FileFormat.objects.get(extension=ext), original_filename = original_filename, contentnode=new_node, file_size=size)
        file_object.save()

        return HttpResponse(json.dumps({
            "success": True,
            "object_id": new_node.pk
        }))
Пример #6
0
    def test_internal_thumbnail(self):
        # Create exercise node (generated images are more predictable)
        node = ContentNode(title="Test Node", kind_id=content_kinds.VIDEO)
        node.save()

        file_data = [{
            "preset": None,
            "filename": str(self.thumbnail_fobj),
            "language": "en",
            "size": self.thumbnail_fobj.file_size,
        }]
        map_files_to_node(self.user, node, file_data)
        self.assertTrue(isinstance(node.thumbnail_encoding, basestring))
        thumbnail_data = json.loads(node.thumbnail_encoding)
        self.assertEqual(thumbnail_data['base64'], generated_base64encoding())
Пример #7
0
    def test_internal_thumbnail(self):
        # Create exercise node (generated images are more predictable)
        node = ContentNode(title="Test Node", kind_id=content_kinds.VIDEO)
        node.save()

        file_data = [{
            "preset": None,
            "filename": str(self.thumbnail_fobj),
            "language": "en",
            "size": self.thumbnail_fobj.file_size,
        }]
        map_files_to_node(self.user, node, file_data)
        self.assertTrue(isinstance(node.thumbnail_encoding, basestring))
        thumbnail_data = json.loads(node.thumbnail_encoding)
        self.assertEqual(thumbnail_data['base64'], generated_base64encoding())
Пример #8
0
    def test_creates_nodes(self):
        """
        Test that it creates a node with the given title and parent.
        """

        # make sure a node with our given self.title exists, with the given parent.
        assert ContentNode.get_nodes_with_title(title=self.title, limit_to_children_of=self.root_node.id).exists()
Пример #9
0
    def test_filter_edit_queryset__orphan_tree__anonymous(self):
        contentnode = create_contentnode(settings.ORPHANAGE_ROOT_ID)

        queryset = ContentNode.filter_edit_queryset(self.base_queryset,
                                                    user=self.anonymous_user)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetDoesNotContain(queryset, pk=contentnode.id)
Пример #10
0
    def test_filter_view_queryset__private_channel(self):
        channel = testdata.channel()
        contentnode = create_contentnode(channel.main_tree_id)

        queryset = ContentNode.filter_view_queryset(self.base_queryset,
                                                    user=self.forbidden_user)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetDoesNotContain(queryset, pk=contentnode.id)

        user = testdata.user()
        channel.viewers.add(user)
        queryset = ContentNode.filter_view_queryset(self.base_queryset,
                                                    user=user)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetContains(queryset, pk=contentnode.id)
Пример #11
0
    def test_filter_edit_queryset__private_channel__anonymous(self):
        channel = testdata.channel()
        contentnode = create_contentnode(channel.main_tree_id)

        queryset = ContentNode.filter_edit_queryset(self.base_queryset,
                                                    user=self.anonymous_user)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetDoesNotContain(queryset, pk=contentnode.id)
Пример #12
0
    def test_filter_view_queryset__public_channel__anonymous(self):
        channel = self.public_channel
        contentnode = create_contentnode(channel.main_tree_id)

        queryset = ContentNode.filter_view_queryset(self.base_queryset,
                                                    user=self.anonymous_user)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetContains(queryset, pk=contentnode.id)
Пример #13
0
    def test_generate_thumbnail(self):
        # Create exercise node (generated images are more predictable)
        node = ContentNode(title="Test Node", kind_id=content_kinds.EXERCISE)
        node.save()

        # Create assessment item with image
        assessment_item = AssessmentItem(contentnode=node)
        assessment_item.save()
        self.thumbnail_fobj.assessment_item = assessment_item
        self.thumbnail_fobj.preset_id = format_presets.EXERCISE_IMAGE
        self.thumbnail_fobj.save()

        # Call generate_thumbnail endpoint
        request = self.create_post_request(reverse_lazy('generate_thumbnail', kwargs={'contentnode_id': node.pk}))
        response = generate_thumbnail(request, node.pk)
        self.assertEqual(response.status_code, 200)
        file_data = json.loads(response.content)
        self.assertEqual(file_data['encoding'], generated_base64encoding())
Пример #14
0
    def test_filter_edit_queryset__orphan_tree(self):
        contentnode = create_contentnode(settings.ORPHANAGE_ROOT_ID)

        user = testdata.user()
        queryset = ContentNode.filter_edit_queryset(self.base_queryset,
                                                    user=user)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetContains(queryset, pk=contentnode.id)
Пример #15
0
 def setUp(self):
     super(ResourceSizeCacheTestCase, self).setUp()
     self.node = mock.Mock(spec_set=ContentNode())
     self.node.pk = "abcdefghijklmnopqrstuvwxyz"
     self.redis_client = mock_class_instance("redis.client.StrictRedis")
     self.cache_client = mock_class_instance(
         "django_redis.client.DefaultClient")
     self.cache_client.get_client.return_value = self.redis_client
     self.cache = mock.Mock(client=self.cache_client)
     self.helper = ResourceSizeCache(self.node, self.cache)
Пример #16
0
    def test_generate_thumbnail(self):
        # Create exercise node (generated images are more predictable)
        node = ContentNode(title="Test Node", kind_id=content_kinds.EXERCISE)
        node.save()

        # Create assessment item with image
        assessment_item = AssessmentItem(contentnode=node)
        assessment_item.save()
        self.thumbnail_fobj.assessment_item = assessment_item
        self.thumbnail_fobj.preset_id = format_presets.EXERCISE_IMAGE
        self.thumbnail_fobj.save()

        # Call generate_thumbnail endpoint
        request = self.create_post_request(
            reverse_lazy('generate_thumbnail',
                         kwargs={'contentnode_id': node.pk}))
        response = generate_thumbnail(request, node.pk)
        self.assertEqual(response.status_code, 200)
        file_data = json.loads(response.content)
        self.assertEqual(file_data['encoding'], generated_base64encoding())
Пример #17
0
    def test_filter_edit_queryset__public_channel__user_id(self):
        channel = self.public_channel
        contentnode = create_contentnode(channel.main_tree_id)

        queryset = ContentNode.filter_edit_queryset(self.base_queryset,
                                                    user_id=987)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetDoesNotContain(queryset, pk=contentnode.id)

        user = testdata.user()
        channel.viewers.add(user)
        queryset = ContentNode.filter_edit_queryset(self.base_queryset,
                                                    user_id=user.id)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetDoesNotContain(queryset, pk=contentnode.id)

        channel.editors.add(user)
        queryset = ContentNode.filter_edit_queryset(self.base_queryset,
                                                    user_id=user.id)
        self.assertQuerysetDoesNotContain(queryset,
                                          pk=settings.ORPHANAGE_ROOT_ID)
        self.assertQuerysetContains(queryset, pk=contentnode.id)
Пример #18
0
def duplicate_nodes_task(
    self,
    user_id,
    channel_id,
    target_id,
    source_id,
    pk=None,
    position="last-child",
    mods=None,
    excluded_descendants=None,
):
    source = ContentNode.objects.get(id=source_id)
    target = ContentNode.objects.get(id=target_id)

    can_edit_source_channel = ContentNode.filter_edit_queryset(
        ContentNode.objects.filter(id=source_id), user_id=user_id).exists()

    new_node = None

    try:
        new_node = source.copy_to(
            target,
            position,
            pk,
            mods,
            excluded_descendants,
            can_edit_source_channel=can_edit_source_channel,
            progress_tracker=self.progress,
        )
    except IntegrityError:
        # This will happen if the node has already been created
        # Pass for now and just return the updated data
        # Possible we might want to raise an error here, but not clear
        # whether this could then be a way to sniff for ids
        pass

    changes = []
    if new_node is not None:
        changes.append(
            generate_update_event(pk, CONTENTNODE, {
                COPYING_FLAG: False,
                "node_id": new_node.node_id
            }))

    return {"changes": changes}
Пример #19
0
    def _check_permissions(self, changes):
        # Filter the passed in contentondes, on both side of the relationship
        allowed_contentnodes = set(
            ContentNode.filter_edit_queryset(
                ContentNode.objects.all(), self.request.user).filter(
                    id__in=list(map(lambda x: x["key"][0], changes)) +
                    list(map(lambda x: x["key"][1], changes))).values_list(
                        "id", flat=True))

        valid_changes = []
        errors = []

        for change in changes:
            if (change["key"][0] in allowed_contentnodes
                    and change["key"][1] in allowed_contentnodes):
                valid_changes.append(change)
            else:
                change.update({"errors": ValidationError("Not found").detail})
                errors.append(change)
        return valid_changes, errors
Пример #20
0
 def test_mptt_refresh(self):
     node_a = testdata.node({"kind_id": "topic", "title": "Node A"})
     node_b = ContentNode(id="abc123", title="Node B")
     self.manager._mptt_refresh(node_a, node_b)
Пример #21
0
def file_create(request):
    if request.method != 'POST':
        return HttpResponseBadRequest(
            "Only POST requests are allowed on this endpoint.")

    original_filename, ext = os.path.splitext(request.FILES.values()[0]._name)
    size = request.FILES.values()[0]._size
    contentfile = DjFile(request.FILES.values()[0])
    checksum = get_hash(contentfile)
    request.user.check_space(size, checksum)

    presets = FormatPreset.objects.filter(
        allowed_formats__extension__contains=ext[1:].lower())
    kind = presets.first().kind
    preferences = json.loads(
        request.POST.get('content_defaults', None) or "{}")

    license = License.objects.filter(
        license_name=preferences.get('license')).first(
        )  # Use filter/first in case preference hasn't been set
    license_id = license.pk if license else None
    new_node = ContentNode(
        title=original_filename,
        kind=kind,
        license_id=license_id,
        author=preferences.get('author') or "",
        aggregator=preferences.get('aggregator') or "",
        provider=preferences.get('provider') or "",
        copyright_holder=preferences.get('copyright_holder'),
        parent_id=settings.ORPHANAGE_ROOT_ID,
    )
    if license and license.is_custom:
        new_node.license_description = preferences.get('license_description')
    # The orphanage is not an actual tree but just a long list of items.
    with ContentNode.objects.disable_mptt_updates():
        new_node.save()
    file_object = File(
        file_on_disk=contentfile,
        checksum=checksum,
        file_format_id=ext[1:].lower(),
        original_filename=request.FILES.values()[0]._name,
        contentnode=new_node,
        file_size=size,
        uploaded_by=request.user,
    )
    file_object.save()

    if kind.pk == content_kinds.VIDEO:
        file_object.preset_id = guess_video_preset_by_resolution(
            str(file_object.file_on_disk))
    elif presets.filter(supplementary=False).count() == 1:
        file_object.preset = presets.filter(supplementary=False).first()
    file_object.save()

    thumbnail = None
    try:
        if preferences.get('auto_derive_video_thumbnail') and new_node.kind_id == content_kinds.VIDEO \
                or preferences.get('auto_derive_audio_thumbnail') and new_node.kind_id == content_kinds.AUDIO \
                or preferences.get('auto_derive_html5_thumbnail') and new_node.kind_id == content_kinds.HTML5 \
                or preferences.get('auto_derive_document_thumbnail') and new_node.kind_id == content_kinds.DOCUMENT:
            thumbnail = generate_thumbnail_from_node(new_node, set_node=True)
            request.user.check_space(thumbnail.file_size, thumbnail.checksum)
    except Exception:
        if thumbnail:
            thumbnail.delete()

    return HttpResponse(
        json.dumps({
            "success":
            True,
            "node":
            JSONRenderer().render(ContentNodeEditSerializer(new_node).data)
        }))
Пример #22
0
def file_create(request):
    if request.method == 'POST':
        original_filename, ext = os.path.splitext(
            request.FILES.values()[0]._name)
        size = request.FILES.values()[0]._size
        contentfile = DjFile(request.FILES.values()[0])
        checksum = get_hash(contentfile)
        request.user.check_space(size, checksum)

        presets = FormatPreset.objects.filter(
            allowed_formats__extension__contains=ext[1:].lower())
        kind = presets.first().kind
        preferences = json.loads(request.META.get('HTTP_PREFERENCES'))
        author = preferences.get('author') or ""
        license = License.objects.filter(
            license_name=preferences.get('license')).first(
            )  # Use filter/first in case preference hasn't been set
        license_id = license.pk if license else None
        new_node = ContentNode(
            title=original_filename,
            kind=kind,
            license_id=license_id,
            author=author,
            copyright_holder=preferences.get('copyright_holder'),
        )
        if license and license.is_custom:
            new_node.license_description = preferences.get(
                'license_description')
        new_node.save()
        file_object = File(
            file_on_disk=contentfile,
            checksum=checksum,
            file_format_id=ext[1:].lower(),
            original_filename=request.FILES.values()[0]._name,
            contentnode=new_node,
            file_size=size,
            uploaded_by=request.user,
        )
        file_object.save()

        if kind.pk == content_kinds.VIDEO:
            file_object.preset_id = guess_video_preset_by_resolution(
                str(file_object.file_on_disk))
        elif presets.filter(supplementary=False).count() == 1:
            file_object.preset = presets.filter(supplementary=False).first()
        file_object.save()

        thumbnail = None
        try:
            if preferences.get('auto_derive_video_thumbnail') and new_node.kind_id == content_kinds.VIDEO \
                    or preferences.get('auto_derive_audio_thumbnail') and new_node.kind_id == content_kinds.AUDIO \
                    or preferences.get('auto_derive_html5_thumbnail') and new_node.kind_id == content_kinds.HTML5 \
                    or preferences.get('auto_derive_document_thumbnail') and new_node.kind_id == content_kinds.DOCUMENT:
                thumbnail = generate_thumbnail_from_node(new_node,
                                                         set_node=True)
                request.user.check_space(thumbnail.file_size,
                                         thumbnail.checksum)
        except Exception:
            if thumbnail:
                thumbnail.delete()

        return HttpResponse(
            json.dumps({
                "success":
                True,
                "node":
                JSONRenderer().render(
                    ContentNodeEditSerializer(new_node).data)
            }))
Пример #23
0
 def setUp(self):
     super(CalculateResourceSizeTestCase, self).setUp()
     self.node = mock.Mock(spec_set=ContentNode())
Пример #24
0
 def test_create_node_null_complete(self):
     new_obj = ContentNode(kind_id=content_kinds.TOPIC)
     try:
         new_obj.save()
     except IntegrityError:
         self.fail("Caused an IntegrityError")
Пример #25
0
def file_create(request):
    if request.method != 'POST':
        return HttpResponseBadRequest("Only POST requests are allowed on this endpoint.")

    original_filename, ext = os.path.splitext(request.FILES.values()[0]._name)
    size = request.FILES.values()[0]._size
    contentfile = DjFile(request.FILES.values()[0])
    checksum = get_hash(contentfile)
    request.user.check_space(size, checksum)

    presets = FormatPreset.objects.filter(allowed_formats__extension__contains=ext[1:].lower())
    kind = presets.first().kind
    preferences = json.loads(request.POST.get('content_defaults', None) or "{}")


    license = License.objects.filter(license_name=preferences.get('license')).first()  # Use filter/first in case preference hasn't been set
    license_id = license.pk if license else None
    new_node = ContentNode(
        title=original_filename,
        kind=kind,
        license_id=license_id,
        author=preferences.get('author') or "",
        aggregator=preferences.get('aggregator') or "",
        provider=preferences.get('provider') or "",
        copyright_holder=preferences.get('copyright_holder'),
        parent_id=settings.ORPHANAGE_ROOT_ID,
    )
    if license and license.is_custom:
        new_node.license_description = preferences.get('license_description')
    new_node.save()
    file_object = File(
        file_on_disk=contentfile,
        checksum=checksum,
        file_format_id=ext[1:].lower(),
        original_filename=request.FILES.values()[0]._name,
        contentnode=new_node,
        file_size=size,
        uploaded_by=request.user,
    )
    file_object.save()

    if kind.pk == content_kinds.VIDEO:
        file_object.preset_id = guess_video_preset_by_resolution(str(file_object.file_on_disk))
    elif presets.filter(supplementary=False).count() == 1:
        file_object.preset = presets.filter(supplementary=False).first()
    file_object.save()

    thumbnail = None
    try:
        if preferences.get('auto_derive_video_thumbnail') and new_node.kind_id == content_kinds.VIDEO \
                or preferences.get('auto_derive_audio_thumbnail') and new_node.kind_id == content_kinds.AUDIO \
                or preferences.get('auto_derive_html5_thumbnail') and new_node.kind_id == content_kinds.HTML5 \
                or preferences.get('auto_derive_document_thumbnail') and new_node.kind_id == content_kinds.DOCUMENT:
            thumbnail = generate_thumbnail_from_node(new_node, set_node=True)
            request.user.check_space(thumbnail.file_size, thumbnail.checksum)
    except Exception:
        if thumbnail:
            thumbnail.delete()

    return HttpResponse(json.dumps({
        "success": True,
        "node": JSONRenderer().render(ContentNodeEditSerializer(new_node).data)
    }))