Beispiel #1
0
    def post(self, request):
        data = JSONParser().parse(request)

        serializer = TopicSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
class FavoriteListCreateSerializer(ModelSerializer):
    topic = TopicSerializer()
    user = UserSerializer()

    class Meta:
        model = FavoriteItem
        fields = ['id', 'topic']
Beispiel #3
0
def topic_list(request):
    # GET list of topics, POST a new topic, DELETE all topics
    if request.method == 'GET':
        topics = Topic.objects.all()

        name = request.GET.get('name', None)
        if name is not None:
            topics = topics.filter(name__icontains=name)

        topics_serializer = TopicSerializer(topics, many=True)
        return JsonResponse(topics_serializer.data, safe=False)

    elif request.method == 'POST':
        topic_data = JSONParser().parse(request)
        topic_serializer = TopicSerializer(data=topic_data)
        if topic_serializer.is_valid():
            topic_serializer.save()
            return JsonResponse(topic_serializer.data,
                                status=status.HTTP_201_CREATED)
    elif request.method == 'DELETE':
        count = Topic.objects.all().delete()
        return JsonResponse(
            {
                'message': '{} Topic were deleted successfully!'.format(
                    count[0])
            },
            status=status.HTTP_204_NO_CONTENT)
    return JsonResponse(topic_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Beispiel #4
0
    def post(self, request, *args, **kwargs):
        data = request.data
        topic = get_object_or_404(
            TopicItem.objects.filter(id=data['topic_id']))
        if FavoriteItem.objects.filter(topic=topic,
                                       user=request.user).exists():
            return Response(data={"message": "Already favorite topic"},
                            status=status.HTTP_409_CONFLICT)

        favorite_item = FavoriteItem(user=request.user, topic=topic)
        favorite_item.save()
        serializer = TopicSerializer(favorite_item.topic,
                                     context={'request': request})
        return Response(serializer.data)
Beispiel #5
0
    def post(self, request, format=None):
        gmapurl = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s' % request.data[
            'zip']
        response = urllib.request.urlopen(gmapurl)
        content = response.read()
        data = json.loads(content.decode("utf8"))

        myzip = zipcode.isequal(request.data['zip'])
        if request.data['scope'] == 'world':
            topic = random.choice(Topic.objects.all())
        else:
            ziplist = zipcode.getzipsinscope(request.data['zip'],
                                             request.data['scope'])
            topic = random.choice(Topic.objects.filter(zip__in=ziplist))

        serialized_topic = TopicSerializer(topic)

        return Response(serialized_topic.data, status=status.HTTP_200_OK)
Beispiel #6
0
class QuestionWithTopAnswerSerializer(serializers.ModelSerializer):

    post = PostSerializer()
    topics = TopicSerializer(many=True)
    answer = serializers.SerializerMethodField('get_top_answer')

    class Meta:
        model = Question
        fields = ('id', 'question', 'topics', 'post', 'answer')

    def get_top_answer(self, obj):
        post = obj.post
        try:
            answer = post.child_posts.all().order_by('-total_vote')[0]
        except:
            answer = None
        serializer = PostSerializer(answer)
        return serializer.data
Beispiel #7
0
 def get(self, request, format=None):
     # Get all topics
     if request.GET.get('keyword') is None:
         topics = Topic.objects.all()
         serializer = SimpleTopicSerializer(topics, many=True)
         return Response(serializer.data)
     # Get all topics related to a keyword
     else:
         topics = [topic.name for topic in list(Topic.objects.all())]
         related_topics = difflib.get_close_matches(
             request.GET.get('keyword'),
             topics,
             10,
             0.2
         )
         result = list(Topic.objects.all().filter(name__in=related_topics))
         result.sort(key=lambda t: related_topics.index(t.name))
         serializer = TopicSerializer(result, many=True)
         return Response(serializer.data)
Beispiel #8
0
    def post(self, request, format=None):
        try:
            if request.data['type'] is 'topic':
                topic = Topic.objects.get(article_link=request.data['url'])
                topic_serializer = TopicSerializer(topic)
                return Response(topic_serializer.data,
                                status=status.HTTP_409_CONFLICT)
            else:
                action = Action.objects.get(article_link=request.data['url'])
                action_serializer = ActionSerializer(action)
                return Response(action_serializer.data,
                                status=status.HTTP_409_CONFLICT)

        except (Topic.DoesNotExist, Action.DoesNotExist) as e:
            try:
                og = opengraph.OpenGraph(url=request.data['url'])
                # Description may or may not exist
                if 'description' in og:
                    desc = og['description']
                else:
                    desc = ''
                if 'title' in og:
                    title = og['title']
                else:
                    title = ''
                return Response(
                    {
                        'image': og['image'],
                        'title': title,
                        'description': desc
                    },
                    status=status.HTTP_200_OK)
            except urllib.error.URLError:
                return Response({'image': 'Invalid URL'},
                                status=status.HTTP_404_NOT_FOUND)
            except KeyError as e:
                return Response({'image': 'Not Found'},
                                status=status.HTTP_404_NOT_FOUND)
Beispiel #9
0
def topic_detail(request, pk):
    # find topic by pk (id)
    try:
        topic = Topic.objects.get(pk=pk)
        if request.method == 'GET':
            topic_serializer = TopicSerializer(topic)
            return JsonResponse(topic_serializer.data)
        elif request.method == 'PUT':
            topic_data = JSONParser().parse(request)
            topic_serializer = TopicSerializer(topic, data=topic_data)
            if topic_serializer.is_valid():
                topic_serializer.save()
                return JsonResponse(topic_serializer.data)
            return JsonResponse(topic_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
        elif request.method == 'DELETE':
            topic.delete()
        return JsonResponse({'message': 'Topic was deleted successfully!'},
                            status=status.HTTP_204_NO_CONTENT)
    except Topic.DoesNotExist:
        return JsonResponse({'message': 'The Topic does not exist'},
                            status=status.HTTP_404_NOT_FOUND)
Beispiel #10
0
    def get(self, request):
        search_term = request.GET.get('search_term')
        sort_type = int(request.GET.get('sort_type'))
        page = int(request.GET['page'])

        splited_term = search_term.split()

        if sort_type == 1:
            q = Question.objects.filter(
                Q(title__icontains=search_term)
                | Q(question_details__icontains=search_term)).distinct(
                ).order_by('-no_of_answers')
            pagination_class = Paginator(q, 5)
            q = pagination_class.page(page)
            serializer = QuestionSerializer(q, many=True)
            return Response(serializer.data)

        if sort_type == 2:
            p = UserOtherDetails.objects.filter(
                Q(user__username__icontains=search_term)
                | Q(user__first_name__icontains=search_term)
                | Q(user__last_name__icontains=search_term)).distinct()
            pagination_class = Paginator(p, 2)
            p = pagination_class.page(page)
            serializer = UserOtherDetailsSerializer(p, many=True)
            return Response(serializer.data)

        if sort_type == 3:
            t = Topic.objects.filter(
                Q(title__icontains=search_term)
                | Q(desc__icontains=search_term)).distinct()
            pagination_class = Paginator(t, 3)
            t = pagination_class.page(page)
            serializer = TopicSerializer(t, many=True)
            return Response(serializer.data)
        return Response(None)
Beispiel #11
0
class SimpleYTVideoSerializer(serializers.ModelSerializer):
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    class Meta:
        model = YTVideo
        exclude = (
            'students',
            'groups',
        )

    def create(self, data):
        topic = data['topic']

        ytvideo = None

        if not topic["id"] is None:
            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                ytvideo_data = data

                pendencies = ytvideo_data["pendencies_resource"]
                del ytvideo_data["pendencies_resource"]

                ytvideo = YTVideo()
                ytvideo.name = ytvideo_data["name"]
                ytvideo.brief_description = ytvideo_data["brief_description"]
                ytvideo.show_window = ytvideo_data["show_window"]
                ytvideo.all_students = ytvideo_data["all_students"]
                ytvideo.visible = ytvideo_data["visible"]
                ytvideo.order = ytvideo_data["order"]
                ytvideo.topic = ytvideo_data["topic"]
                ytvideo.url = ytvideo_data["url"]

                ytvideo.save()

                tags = data["tags"]

                for tag in tags:
                    if not tag["name"] == "":
                        if tag["id"] == "":
                            tag = Tag.objects.create(name=tag["name"])
                        else:
                            tag = get_object_or_404(Tag, id=tag["id"])

                        ytvideo.tags.add(tag)

                resource = get_object_or_404(Resource, id=ytvideo.id)

                for pend in pendencies:
                    Pendencies.objects.create(resource=resource, **pend)

        return ytvideo

    def update(self, instance, data):
        return instance
Beispiel #12
0
class SimpleQuestionarySerializer(serializers.ModelSerializer):
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)
    spec_questionary = SpecificationSerializer(many=True)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    class Meta:
        model = Questionary
        exclude = (
            'students',
            'groups',
        )

    def create(self, data):
        topic = data['topic']

        questionary = None

        if not topic["id"] is None:
            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                questionary_data = data

                pendencies = questionary_data["pendencies_resource"]
                del questionary_data["pendencies_resource"]

                specifications = questionary_data["spec_questionary"]
                del questionary_data["spec_questionary"]

                questionary = Questionary()
                questionary.name = questionary_data["name"]
                questionary.brief_description = questionary_data[
                    "brief_description"]
                questionary.show_window = questionary_data["show_window"]
                questionary.all_students = questionary_data["all_students"]
                questionary.visible = questionary_data["visible"]
                questionary.order = questionary_data["order"]
                questionary.topic = questionary_data["topic"]
                questionary.presentation = questionary_data["presentation"]
                questionary.data_ini = questionary_data["data_ini"]
                questionary.data_end = questionary_data["data_end"]

                questionary.save()

                tags = data["tags"]

                for tag in tags:
                    if not tag["name"] == "":
                        if tag["id"] == "":
                            tag = Tag.objects.create(name=tag["name"])
                        else:
                            tag = get_object_or_404(Tag, id=tag["id"])

                        questionary.tags.add(tag)

                for spec in specifications:
                    tags = spec["categories"]

                    specs = Specification.objects.create(
                        questionary=questionary,
                        n_questions=spec["n_questions"])

                    for tag in tags:
                        if not tag["name"] == "":
                            if tag["id"] == "":
                                tag = Tag.objects.create(name=tag["name"])
                            else:
                                tag = get_object_or_404(Tag, id=tag["id"])

                            specs.categories.add(tag)

                resource = get_object_or_404(Resource, id=questionary.id)

                for pend in pendencies:
                    Pendencies.objects.create(resource=resource, **pend)

        return questionary

    def update(self, instance, data):
        return instance
Beispiel #13
0
 def get(self, request):
     topics = Topic.objects.all()
     data = TopicSerializer(topics, many=True).data
     return Response(data)
Beispiel #14
0
class CompleteYTVideoSerializer(serializers.ModelSerializer):
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)
    groups = StudentsGroupSerializer('get_files', many=True)
    students = UserBackupSerializer('get_files', many=True)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    def get_files(self, obj):
        files = self.context.get("files", None)

        return files

    class Meta:
        model = YTVideo
        fields = '__all__'

    def create(self, data):
        topic = data['topic']

        ytvideo = None

        if not topic["id"] is None:
            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                ytvideo_data = data

                pendencies = ytvideo_data["pendencies_resource"]
                del ytvideo_data["pendencies_resource"]

                ytvideo = YTVideo()
                ytvideo.name = ytvideo_data["name"]
                ytvideo.brief_description = ytvideo_data["brief_description"]
                ytvideo.show_window = ytvideo_data["show_window"]
                ytvideo.all_students = ytvideo_data["all_students"]
                ytvideo.visible = ytvideo_data["visible"]
                ytvideo.order = ytvideo_data["order"]
                ytvideo.topic = ytvideo_data["topic"]
                ytvideo.url = ytvideo_data["url"]

                ytvideo.save()

                tags = data["tags"]

                for tag in tags:
                    if not tag["name"] == "":
                        if tag["id"] == "":
                            tag = Tag.objects.create(name=tag["name"])
                        else:
                            tag = get_object_or_404(Tag, id=tag["id"])

                        ytvideo.tags.add(tag)

                students = data["students"]
                subject = get_object_or_404(Subject,
                                            slug=self.context.get(
                                                "subject", None))

                for student_data in students:
                    logs = student_data["get_items"]

                    if student_data["id"] == "":
                        u_exist = User.objects.filter(
                            email=student_data["email"])

                        if not u_exist.exists():
                            student = u_exist[0]

                            for log in logs:
                                log["user_id"] = student.id

                                l_exists = Log.objects.filter(
                                    user_id=log["user_id"],
                                    user=log["user"],
                                    user_email=log["user_email"],
                                    action=log["action"],
                                    resource=log["resource"],
                                    component=log["component"],
                                    context=log["context"])

                                if not l_exists.exists():
                                    Log.objects.create(**log)
                        else:
                            student = User()
                            student.email = student_data["email"]
                            student.username = student_data["username"]
                            student.last_name = student_data["last_name"]
                            student.social_name = student_data["social_name"]
                            student.show_email = student_data["show_email"]
                            student.is_staff = student_data["is_staff"]
                            student.is_active = student_data["is_active"]
                            student.image = student_data["image"]

                            student.save()

                            for log in logs:
                                log["user_id"] = student.id

                                Log.objects.create(**log)
                    else:
                        student = get_object_or_404(User,
                                                    id=student_data["id"])

                        for log in logs:
                            l_exists = Log.objects.filter(
                                user_id=log["user_id"],
                                user=log["user"],
                                user_email=log["user_email"],
                                action=log["action"],
                                resource=log["resource"],
                                component=log["component"],
                                context=log["context"])

                            if not l_exists.exists():
                                Log.objects.create(**log)

                    ytvideo.students.add(student)
                    subject.students.add(student)

                groups = data["groups"]

                for group_data in groups:
                    g_exists = StudentsGroup.objects.filter(
                        subject=subject, slug=group_data["slug"])

                    if g_exists.exists():
                        group = g_exists[0]
                    else:
                        group = StudentsGroup()
                        group.name = group_data["name"]
                        group.description = group_data["description"]
                        group.subject = subject

                        group.save()

                        for participant in group_data["participants"]:
                            p_user = get_object_or_404(
                                User, email=participant["email"])

                            group.participants.add(p_user)

                    ytvideo.groups.add(group)

                resource = get_object_or_404(Resource, id=ytvideo.id)

                for pend in pendencies:
                    Pendencies.objects.create(resource=resource, **pend)

        return ytvideo
Beispiel #15
0
class SimpleFileLinkSerializer(serializers.ModelSerializer):
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)
    file_content = serializers.CharField(required=False,
                                         allow_blank=True,
                                         max_length=255)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    def validate(self, data):
        files = self.context.get('files', None)

        if files:
            if data["file_content"] in files.namelist():
                file_path = os.path.join(settings.MEDIA_ROOT,
                                         data["file_content"])

                if os.path.isfile(file_path):
                    dst_path = os.path.join(settings.MEDIA_ROOT, "tmp")

                    path = files.extract(data["file_content"], dst_path)

                    new_name = os.path.join(
                        "files", "file_" + str(time.time()) +
                        os.path.splitext(data["file_content"])[1])

                    os.rename(os.path.join(dst_path, path),
                              os.path.join(settings.MEDIA_ROOT, new_name))

                    data["file_content"] = new_name
                else:
                    path = files.extract(data["file_content"],
                                         settings.MEDIA_ROOT)
            else:
                data["file_content"] = None
        else:
            data["file_content"] = None

        return data

    class Meta:
        model = FileLink
        extra_kwargs = {
            "file_content": {
                "required": False,
                "validators": [],
            },
        }
        exclude = (
            'students',
            'groups',
        )
        validators = []

    def create(self, data):
        topic = data['topic']

        file_link = None

        if not topic["id"] is None:
            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                file_link_data = data

                pendencies = file_link_data["pendencies_resource"]
                del file_link_data["pendencies_resource"]

                file_link = FileLink()
                file_link.name = file_link_data["name"]
                file_link.brief_description = file_link_data[
                    "brief_description"]
                file_link.show_window = file_link_data["show_window"]
                file_link.all_students = file_link_data["all_students"]
                file_link.visible = file_link_data["visible"]
                file_link.order = file_link_data["order"]
                file_link.topic = file_link_data["topic"]
                file_link.file_content = file_link_data["file_content"]

                file_link.save()

                tags = data["tags"]

                for tag in tags:
                    if not tag["name"] == "":
                        if tag["id"] == "":
                            tag = Tag.objects.create(name=tag["name"])
                        else:
                            tag = get_object_or_404(Tag, id=tag["id"])

                        file_link.tags.add(tag)

                resource = get_object_or_404(Resource, id=file_link.id)

                for pend in pendencies:
                    Pendencies.objects.create(resource=resource, **pend)

        return file_link

    def update(self, instance, data):
        return instance
Beispiel #16
0
 def get(self, request, pk):
     topic = Topic.objects.get(pk=pk)
     topic_data = TopicSerializer(topic).data
     return Response(topic_data)
Beispiel #17
0
class CompleteFileLinkSerializer(serializers.ModelSerializer):
    file_content = serializers.CharField(required=False,
                                         allow_blank=True,
                                         max_length=255)
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)
    groups = StudentsGroupSerializer('get_files', many=True)
    students = UserBackupSerializer('get_files', many=True)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    def get_files(self, obj):
        files = self.context.get("files", None)

        return files

    def validate(self, data):
        files = self.context.get('files', None)

        if files:
            if data["file_content"] in files.namelist():
                file_path = os.path.join(settings.MEDIA_ROOT,
                                         data["file_content"])

                if os.path.isfile(file_path):
                    dst_path = os.path.join(settings.MEDIA_ROOT, "tmp")

                    path = files.extract(data["file_content"], dst_path)

                    new_name = os.path.join(
                        "files", "file_" + str(time.time()) +
                        os.path.splitext(data["file_content"])[1])

                    os.rename(os.path.join(dst_path, path),
                              os.path.join(settings.MEDIA_ROOT, new_name))

                    data["file_content"] = new_name
                else:
                    path = files.extract(data["file_content"],
                                         settings.MEDIA_ROOT)
            else:
                data["file_content"] = None
        else:
            data["file_content"] = None

        return data

    class Meta:
        model = FileLink
        fields = '__all__'

    def create(self, data):
        topic = data['topic']

        file_link = None

        if not topic["id"] is None:
            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                file_link_data = data

                pendencies = file_link_data["pendencies_resource"]
                del file_link_data["pendencies_resource"]

                file_link = FileLink()
                file_link.name = file_link_data["name"]
                file_link.brief_description = file_link_data[
                    "brief_description"]
                file_link.show_window = file_link_data["show_window"]
                file_link.all_students = file_link_data["all_students"]
                file_link.visible = file_link_data["visible"]
                file_link.order = file_link_data["order"]
                file_link.topic = file_link_data["topic"]
                file_link.file_content = file_link_data["file_content"]

                file_link.save()

                tags = data["tags"]

                for tag in tags:
                    if not tag["name"] == "":
                        if tag["id"] == "":
                            tag = Tag.objects.create(name=tag["name"])
                        else:
                            tag = get_object_or_404(Tag, id=tag["id"])

                        file_link.tags.add(tag)

                students = data["students"]
                subject = get_object_or_404(Subject,
                                            slug=self.context.get(
                                                "subject", None))

                for student_data in students:
                    logs = student_data["get_items"]

                    if student_data["id"] == "":
                        u_exist = User.objects.filter(
                            email=student_data["email"])

                        if not u_exist.exists():
                            student = u_exist[0]

                            for log in logs:
                                log["user_id"] = student.id

                                l_exists = Log.objects.filter(
                                    user_id=log["user_id"],
                                    user=log["user"],
                                    user_email=log["user_email"],
                                    action=log["action"],
                                    resource=log["resource"],
                                    component=log["component"],
                                    context=log["context"])

                                if not l_exists.exists():
                                    Log.objects.create(**log)
                        else:
                            student = User()
                            student.email = student_data["email"]
                            student.username = student_data["username"]
                            student.last_name = student_data["last_name"]
                            student.social_name = student_data["social_name"]
                            student.show_email = student_data["show_email"]
                            student.is_staff = student_data["is_staff"]
                            student.is_active = student_data["is_active"]
                            student.image = student_data["image"]

                            student.save()

                            for log in logs:
                                log["user_id"] = student.id

                                Log.objects.create(**log)
                    else:
                        student = get_object_or_404(User,
                                                    id=student_data["id"])

                        for log in logs:
                            l_exists = Log.objects.filter(
                                user_id=log["user_id"],
                                user=log["user"],
                                user_email=log["user_email"],
                                action=log["action"],
                                resource=log["resource"],
                                component=log["component"],
                                context=log["context"])

                            if not l_exists.exists():
                                Log.objects.create(**log)

                    file_link.students.add(student)
                    subject.students.add(student)

                groups = data["groups"]

                for group_data in groups:
                    g_exists = StudentsGroup.objects.filter(
                        subject=subject, slug=group_data["slug"])

                    if g_exists.exists():
                        group = g_exists[0]
                    else:
                        group = StudentsGroup()
                        group.name = group_data["name"]
                        group.description = group_data["description"]
                        group.subject = subject

                        group.save()

                        for participant in group_data["participants"]:
                            p_user = get_object_or_404(
                                User, email=participant["email"])

                            group.participants.add(p_user)

                    file_link.groups.add(group)

                resource = get_object_or_404(Resource, id=file_link.id)

                for pend in pendencies:
                    Pendencies.objects.create(resource=resource, **pend)

        return file_link
Beispiel #18
0
class CompleteH5PSerializer(serializers.ModelSerializer):
    file = serializers.CharField(required=False,
                                 allow_blank=True,
                                 max_length=255)
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)
    groups = StudentsGroupSerializer('get_files', many=True)
    students = UserBackupSerializer('get_files', many=True)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    def get_files(self, obj):
        files = self.context.get("files", None)

        return files

    def validate(self, data):
        files = self.context.get('files', None)

        if files:
            if data["file"] in files.namelist():
                file_path = os.path.join(settings.MEDIA_ROOT, data["file"])

                if os.path.isfile(file_path):
                    dst_path = os.path.join(settings.MEDIA_ROOT, "tmp")
                    h5p_helper_path = os.path.join(settings.MEDIA_ROOT, 'h5pp',
                                                   'tmp')

                    if not os.path.exists(h5p_helper_path):
                        os.makedirs(h5p_helper_path)

                    path = files.extract(data["file"], dst_path)
                    tmph5pfile = files.extract(data["file"], h5p_helper_path)

                    new_name = os.path.join(
                        "h5p_resource", "file_" + str(time.time()) +
                        os.path.splitext(data["file"])[1])

                    os.rename(os.path.join(dst_path, path),
                              os.path.join(settings.MEDIA_ROOT, new_name))
                    os.rename(
                        tmph5pfile,
                        os.path.join(h5p_helper_path,
                                     os.path.split(data["file"])[1]))

                    data["tmph5pfile"] = os.path.join(
                        h5p_helper_path,
                        os.path.split(data["file"])[1])
                    data["folderpath"] = h5p_helper_path
                    data["file"] = new_name

                    if os.path.exists(
                            os.path.join(h5p_helper_path, "h5p_resource")):
                        os.rmdir(os.path.join(h5p_helper_path, "h5p_resource"))
                else:
                    path = files.extract(data["file"], settings.MEDIA_ROOT)
            else:
                data["file"] = None
        else:
            data["file"] = None

        return data

    class Meta:
        model = H5P
        fields = '__all__'

    def create(self, data):
        topic = data['topic']

        request = self.context.get('request', None)

        h5p = None

        if not topic["id"] is None:

            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                h5p_data = data

                pendencies = h5p_data["pendencies_resource"]
                del h5p_data["pendencies_resource"]

                if h5p_data["tmph5pfile"]:
                    interface = H5PDjango(request.user)
                    validator = interface.h5pGetInstance(
                        'validator', h5p_data['folderpath'],
                        h5p_data['tmph5pfile'])

                    if validator.isValidPackage(False, False):
                        _mutable = request.POST._mutable

                        request.POST._mutable = True

                        request.POST["name"] = h5p_data["name"]
                        request.POST['file_uploaded'] = True
                        request.POST['disable'] = 0
                        request.POST['author'] = request.user.username
                        request.POST['h5p_upload'] = h5p_data['tmph5pfile']
                        request.POST['h5p_upload_folder'] = h5p_data[
                            'folderpath']

                        request.POST._mutable = _mutable

                        if h5pInsert(request, interface):
                            contentResource = h5p_contents.objects.all(
                            ).order_by('-content_id')[0]

                            h5p = H5P()
                            h5p.name = h5p_data["name"]
                            h5p.brief_description = h5p_data[
                                "brief_description"]
                            h5p.show_window = h5p_data["show_window"]
                            h5p.all_students = h5p_data["all_students"]
                            h5p.visible = h5p_data["visible"]
                            h5p.order = h5p_data["order"]
                            h5p.topic = h5p_data["topic"]
                            h5p.file = h5p_data["file"]
                            h5p.data_ini = h5p_data["data_ini"]
                            h5p.data_end = h5p_data["data_end"]
                            h5p.h5p_resource = contentResource

                            h5p.save()

                            tags = data["tags"]

                            for tag in tags:
                                if not tag["name"] == "":
                                    if tag["id"] == "":
                                        tag = Tag.objects.create(
                                            name=tag["name"])
                                    else:
                                        tag = get_object_or_404(Tag,
                                                                id=tag["id"])

                                    h5p.tags.add(tag)

                            students = data["students"]
                            subject = get_object_or_404(Subject,
                                                        slug=self.context.get(
                                                            "subject", None))

                            for student_data in students:
                                logs = student_data["get_items"]

                                if student_data["id"] == "":
                                    u_exist = User.objects.filter(
                                        email=student_data["email"])

                                    if not u_exist.exists():
                                        student = u_exist[0]

                                        for log in logs:
                                            log["user_id"] = student.id

                                            l_exists = Log.objects.filter(
                                                user_id=log["user_id"],
                                                user=log["user"],
                                                user_email=log["user_email"],
                                                action=log["action"],
                                                resource=log["resource"],
                                                component=log["component"],
                                                context=log["context"])

                                            if not l_exists.exists():
                                                Log.objects.create(**log)
                                    else:
                                        student = User()
                                        student.email = student_data["email"]
                                        student.username = student_data[
                                            "username"]
                                        student.last_name = student_data[
                                            "last_name"]
                                        student.social_name = student_data[
                                            "social_name"]
                                        student.show_email = student_data[
                                            "show_email"]
                                        student.is_staff = student_data[
                                            "is_staff"]
                                        student.is_active = student_data[
                                            "is_active"]
                                        student.image = student_data["image"]

                                        student.save()

                                        for log in logs:
                                            log["user_id"] = student.id

                                            Log.objects.create(**log)
                                else:
                                    student = get_object_or_404(
                                        User, id=student_data["id"])

                                    for log in logs:
                                        l_exists = Log.objects.filter(
                                            user_id=log["user_id"],
                                            user=log["user"],
                                            user_email=log["user_email"],
                                            action=log["action"],
                                            resource=log["resource"],
                                            component=log["component"],
                                            context=log["context"])

                                        if not l_exists.exists():
                                            Log.objects.create(**log)

                                h5p.students.add(student)
                                subject.students.add(student)

                            groups = data["groups"]

                            for group_data in groups:
                                g_exists = StudentsGroup.objects.filter(
                                    subject=subject, slug=group_data["slug"])

                                if g_exists.exists():
                                    group = g_exists[0]
                                else:
                                    group = StudentsGroup()
                                    group.name = group_data["name"]
                                    group.description = group_data[
                                        "description"]
                                    group.subject = subject

                                    group.save()

                                    for participant in group_data[
                                            "participants"]:
                                        p_user = get_object_or_404(
                                            User, email=participant["email"])

                                        group.participants.add(p_user)

                                h5p.groups.add(group)

                            resource = get_object_or_404(Resource, id=h5p.id)

                            for pend in pendencies:
                                Pendencies.objects.create(resource=resource,
                                                          **pend)

        return h5p
Beispiel #19
0
class SimpleH5PSerializer(serializers.ModelSerializer):
    topic = TopicSerializer('get_subject')
    tags = TagSerializer(many=True)
    pendencies_resource = PendenciesSerializer(many=True)
    file = serializers.CharField(required=False,
                                 allow_blank=True,
                                 max_length=255)

    def get_subject(self, obj):
        subject = self.context.get("subject", None)

        return subject

    def validate(self, data):
        files = self.context.get('files', None)

        if files:
            print(data["file"])
            print(files.namelist())
            if data["file"] in files.namelist():
                file_path = os.path.join(settings.MEDIA_ROOT, data["file"])

                if os.path.isfile(file_path):
                    dst_path = os.path.join(settings.MEDIA_ROOT, "tmp")
                    h5p_helper_path = os.path.join(settings.MEDIA_ROOT, 'h5pp',
                                                   'tmp')

                    if not os.path.exists(h5p_helper_path):
                        os.makedirs(h5p_helper_path)

                    path = files.extract(data["file"], dst_path)
                    tmph5pfile = files.extract(data["file"], h5p_helper_path)
                    print(tmph5pfile)
                    new_name = os.path.join(
                        "h5p_resource", "file_" + str(time.time()) +
                        os.path.splitext(data["file"])[1])

                    os.rename(os.path.join(dst_path, path),
                              os.path.join(settings.MEDIA_ROOT, new_name))
                    os.rename(
                        tmph5pfile,
                        os.path.join(h5p_helper_path,
                                     os.path.split(data["file"])[1]))

                    data["tmph5pfile"] = os.path.join(
                        h5p_helper_path,
                        os.path.split(data["file"])[1])
                    data["folderpath"] = h5p_helper_path
                    data["file"] = new_name

                    if os.path.exists(
                            os.path.join(h5p_helper_path, "h5p_resource")):
                        os.rmdir(os.path.join(h5p_helper_path, "h5p_resource"))

                else:
                    path = files.extract(data["file"], settings.MEDIA_ROOT)
            else:
                data["file"] = None
        else:
            data["file"] = None

        return data

    class Meta:
        model = H5P
        exclude = (
            'students',
            'groups',
        )

    def create(self, data):
        topic = data['topic']

        request = self.context.get('request', None)

        h5p = None

        if not topic["id"] is None:
            if "subject" in topic:
                r_exits = Resource.objects.filter(
                    topic__subject=topic["subject"],
                    name__unaccent__iexact=data["name"])
            else:
                r_exits = Resource.objects.filter(
                    topic__subject__id=topic["subject_id"],
                    name__unaccent__iexact=data["name"])

            if not r_exits.exists():
                if topic['id'] == "":
                    topic_exist = Topic.objects.filter(
                        subject=topic['subject'],
                        name__unaccent__iexact=topic["name"])

                    if topic_exist.exists():
                        topic = topic_exist[0]
                    else:
                        topic = Topic.objects.create(
                            name=topic['name'],
                            subject=topic['subject'],
                            repository=topic['repository'],
                            visible=topic['visible'],
                            order=topic['order'],
                            description=topic['description'])

                    data["topic"] = topic
                else:
                    data["topic"] = get_object_or_404(Topic, id=topic["id"])

                h5p_data = data

                pendencies = h5p_data["pendencies_resource"]
                del h5p_data["pendencies_resource"]

                if h5p_data["tmph5pfile"]:
                    interface = H5PDjango(request.user)
                    validator = interface.h5pGetInstance(
                        'validator', h5p_data['folderpath'],
                        h5p_data['tmph5pfile'])

                    if validator.isValidPackage(False, False):
                        _mutable = request.POST._mutable

                        request.POST._mutable = True

                        request.POST["name"] = h5p_data["name"]
                        request.POST['file_uploaded'] = True
                        request.POST['disable'] = 0
                        request.POST['author'] = request.user.username
                        request.POST['h5p_upload'] = h5p_data['tmph5pfile']
                        request.POST['h5p_upload_folder'] = h5p_data[
                            'folderpath']

                        request.POST._mutable = _mutable

                        if h5pInsert(request, interface):
                            contentResource = h5p_contents.objects.all(
                            ).order_by('-content_id')[0]

                            h5p = H5P()
                            h5p.name = h5p_data["name"]
                            h5p.brief_description = h5p_data[
                                "brief_description"]
                            h5p.show_window = h5p_data["show_window"]
                            h5p.all_students = h5p_data["all_students"]
                            h5p.visible = h5p_data["visible"]
                            h5p.order = h5p_data["order"]
                            h5p.topic = h5p_data["topic"]
                            h5p.file = h5p_data["file"]
                            h5p.data_ini = h5p_data["data_ini"]
                            h5p.data_end = h5p_data["data_end"]
                            h5p.h5p_resource = contentResource

                            h5p.save()

                            tags = data["tags"]

                            for tag in tags:
                                if not tag["name"] == "":
                                    if tag["id"] == "":
                                        tag = Tag.objects.create(
                                            name=tag["name"])
                                    else:
                                        tag = get_object_or_404(Tag,
                                                                id=tag["id"])

                                    h5p.tags.add(tag)

                            resource = get_object_or_404(Resource, id=h5p.id)

                            for pend in pendencies:
                                Pendencies.objects.create(resource=resource,
                                                          **pend)

        return h5p

    def update(self, instance, data):
        return instance
Beispiel #20
0
 def get(self, request, topic_id, format=None):
     # Get specific topic with id
     topic = Topic.objects.get(pk=topic_id)
     serializer = TopicSerializer(topic)
     return Response(serializer.data)
Beispiel #21
0
class SimpleGoalSerializer(serializers.ModelSerializer):
	topic = TopicSerializer('get_subject')
	tags = TagSerializer(many = True)
	item_goal = GoalItemSerializer(many = True)
	pendencies_resource = PendenciesSerializer(many = True)

	def get_subject(self, obj):
		subject = self.context.get("subject", None)

		return subject

	class Meta:
		model = Goals
		extra_kwargs = {
			"tags": {
				"validators": [],
			},
		}
		exclude = ('students', 'groups',)
		validators = []

	def create(self, data):
		topic = data['topic']

		goals = None

		if not topic["id"] is None:
			if "subject" in topic:
				r_exits = Resource.objects.filter(topic__subject = topic["subject"], name__unaccent__iexact = data["name"])
			else:
				r_exits = Resource.objects.filter(topic__subject__id = topic["subject_id"], name__unaccent__iexact = data["name"])

			if not r_exits.exists():
				if topic['id'] == "":
					topic_exist = Topic.objects.filter(subject = topic['subject'], name__unaccent__iexact = topic["name"])

					if topic_exist.exists():
						topic = topic_exist[0]
					else:
						topic = Topic.objects.create(name = topic['name'], subject = topic['subject'], repository = topic['repository'], visible = topic['visible'], order = topic['order'], description = topic['description'])
					
					data["topic"] = topic
				else:
					data["topic"] = get_object_or_404(Topic, id = topic["id"])

				goals_data = data
				
				pendencies = goals_data["pendencies_resource"]
				del goals_data["pendencies_resource"]

				goal_items = goals_data["item_goal"]
				del goals_data["item_goal"]

				goals = Goals()
				goals.name = goals_data["name"]
				goals.brief_description = goals_data["brief_description"]
				goals.show_window = goals_data["show_window"]
				goals.all_students = goals_data["all_students"]
				goals.visible = goals_data["visible"]
				goals.order = goals_data["order"]
				goals.topic = goals_data["topic"]
				goals.presentation = goals_data["presentation"]
				goals.limit_submission_date = goals_data["limit_submission_date"]

				goals.save()
				
				tags = data["tags"]

				for tag in tags:
					if not tag["name"] == "":
						if tag["id"] == "":
							tag = Tag.objects.create(name = tag["name"])
						else:
							tag = get_object_or_404(Tag, id = tag["id"])

						goals.tags.add(tag)

				resource = get_object_or_404(Resource, id = goals.id)

				for item in goal_items:
					GoalItem.objects.create(goal = goals, **item)

				for pend in pendencies:
					Pendencies.objects.create(resource = resource, **pend)

		return goals

	def update(self, instance, data):
		return instance