Fakultas Ilmu Komputer UI

views.py 19.1 KB
Newer Older
1
2
3
4
import mimetypes
import os

from django.conf import settings
5
from django.contrib.auth.models import AnonymousUser
6
from django.contrib import messages
7
from django.core import serializers
8
from django.core.exceptions import PermissionDenied, ValidationError
9
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
10
from django.db.models import Q
11
12
13
14
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
from django.shortcuts import get_object_or_404, redirect, render
from django.template import loader
15
from django.urls import reverse
igor lestin sianipar's avatar
igor lestin sianipar committed
16
from django.views.generic import TemplateView, ListView
17
from .models import Category, Comment, Materi
igor lestin sianipar's avatar
igor lestin sianipar committed
18
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
19
from administration.models import VerificationReport
20
21
from app.forms import SuntingProfilForm, UploadMateriForm
from app.models import Category, Comment, Materi, Like, ViewStatistics, DownloadStatistics
22
from authentication.models import User
23

24
25

class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
26
    paginate_by = 2
27
28
29
30
31
32
33
    template_name = "app/katalog_materi.html"

    def get_context_data(self, **kwargs):
        return super().get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
34
        context["kategori_list"] = Category.objects.all()
35
        try:
36
37
            context["materi_list"] = Materi.objects.all().filter(
                status="APPROVE")
38
39
        except:
            context["materi_list"] = None
40

41
        getSearch = request.GET.get('search')
42
        if getSearch:
43
            list = Materi.objects.filter(
44
                Q(title__icontains=getSearch) |
45
                Q(author__icontains=getSearch) |
46
47
                Q(uploader__name__icontains=getSearch) |
                Q(descriptions__icontains=getSearch) |
48
                Q(publisher__icontains=getSearch)
49
50
            ).distinct()
            context["materi_list"] = list.filter(status="APPROVE")
Saul Andre's avatar
Saul Andre committed
51

52
53
54
        getKategori = request.GET.get("kategori")
        if getKategori:
            pkGet = request.GET.get("kategori")
55
56
57
58
            kategori = Category.objects.get(pk=pkGet)
            list = Materi.objects.filter(categories=kategori.pk)
            context["materi_list"] = list.filter(status="APPROVE")

59
        getSort = request.GET.get("sort")
60
61
        if getSort:
            list = Materi.objects.all().filter(status="APPROVE")
62
63
64
65
66
67
            if(getSort == "judul"):
                context["materi_list"] = list.order_by('title')
            elif(getSort == "penulis"):
                context["materi_list"] = list.order_by('author')
            elif(getSort == "pengunggah"):
                context["materi_list"] = list.order_by('uploader')
68

69
70
        return self.render_to_response(context=context)

71

72
73
74
75
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
76
77
78
79
80
81
        context = super(DetailMateri, self).get_context_data(**kwargs)
        if not self.request.session or not self.request.session.session_key:
            self.request.session.save()
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
        context["session_id"] = self.request.session.session_key
        context["materi_data"] = materi
82
        context["report"] = VerificationReport.objects.filter(materi=materi)
83
84
85
        context["has_liked"] = Like.objects.filter(
            materi=materi, session_id=self.request.session.session_key).exists()
        return context
86
87
88

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
89
90
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
91
        context["comment_data"] = query_set_for_comment
92
93
        return self.render_to_response(context=context)

94
95
    def get_user_name(self, request):
        user_name = ""
96
97
98
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
99
100
101
102
103
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

104
    def post(self, request, *args, **kwargs):
105
        commentText = request.POST.get("comment", None)
106
        if commentText == None or commentText == "":
107
108
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
109
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
110
111
            query_set_for_comment = Comment.objects.filter(
                materi=context["materi_data"])
112
            context["comment_data"] = query_set_for_comment
113
            return self.render_to_response(context=context)
114

115
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
116
117
118
        user_obj = request.user if request.user.is_authenticated else None
        comment = Comment.objects.create(comment=commentText,
                                         username=self.get_user_name(request), materi=materi, user=user_obj)
119
120
121
        comment.save()
        return HttpResponseRedirect(request.path)

122

123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def toggle_like(request):
    if request.method == 'POST':
        materi_id = request.POST.get('materi_id', None)
        session_id = request.POST.get('session_id', None)
        if materi_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        materi = get_object_or_404(Materi, pk=materi_id)
        has_liked = Like.objects.filter(
            materi=materi, session_id=session_id).exists()
        if has_liked:
            like = get_object_or_404(
                Like, materi=materi, session_id=session_id)
            like.delete()
            return JsonResponse({"success": True, "liked": True})
        else:
            Like(materi=materi, session_id=session_id).save()
            return JsonResponse({"success": True, "liked": False})
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method"})


144
145
146
147
148
149
def delete_comment(request, pk_materi, pk_comment):
    comment = get_object_or_404(Comment, pk=pk_comment)
    url = '/materi/' + str(pk_materi) + "/"
    comment.delete()
    return HttpResponseRedirect(url)

150

151
152
153
154
155
def download_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
    path = materi.content.path
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
156
157
158
159
160
161
162
163
164
165
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
                response["Content-Disposition"] = "attachment; filename=" + \
                    os.path.basename(file_path)
                DownloadStatistics(materi=materi).save()
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
166
167
168
169
170
171
172
173
174
    else:
        raise Http404("File tidak dapat ditemukan.")

def view_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
    path = materi.content.path
    file_path = os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        mimetype = mimetypes.guess_type(file_path)
175
176
177
178
179
180
181
182
183
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
                response["Content-Disposition"] = "inline; filename=" + \
                    os.path.basename(file_path)
                ViewStatistics(materi=materi).save()
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
184
185
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
186
187

class UploadMateriView(TemplateView):
188
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
189
190
191
192
193
194
    context = {}

    def get_context_data(self, **kwargs):
        context = super(UploadMateriView, self).get_context_data(**kwargs)
        return context

Saul Andre's avatar
Saul Andre committed
195
    def post(self, request, *args, **kwargs):
igor lestin sianipar's avatar
igor lestin sianipar committed
196
197
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
198
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
199
200
201
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
202
203
204
205
206
207
            konten = form.cleaned_data['content']
            try:
                self.validate_file_extension(konten)
            except ValidationError:
                messages.error(request, "Materi gagal diunggah, format file tidak sesuai")
                return HttpResponseRedirect("/unggah/")
igor lestin sianipar's avatar
igor lestin sianipar committed
208
            materi.save()
209
210
211
            kateg = form.cleaned_data['categories']
            for i in kateg:
                materi.categories.add(i)
212
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
213
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
214
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
215
            context = self.get_context_data(**kwargs)
216
            context["form"] = form
217
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
218
219
220
221
222
223
            return self.render_to_response(context)

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
        context = self.get_context_data(**kwargs)
224
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
225
        return self.render_to_response(context)
226
227
228
229
230
231
    
    def validate_file_extension(self, value):
        ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
        valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls', '.mp4', '.mp3']
        if not ext.lower() in valid_extensions:
            raise ValidationError('Unsupported file extension.')
232

Samuel Dimas's avatar
Samuel Dimas committed
233

234
235
236
237
238
239
240
241
242
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


243
class DashboardKontributorView(TemplateView):
244
    template_name = "dashboard.html"
245
246
247
248
249
250
251

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(DashboardKontributorView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
252
253
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
254
255
256
257
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
258
259
260
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
261
        return self.render_to_response(context)
262

263

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
class ProfilAdminView(TemplateView):
    template_name = "profil-admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_admin:
            raise PermissionDenied(request)
        return super(ProfilAdminView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProfilAdminView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        current_user = self.request.user
        context["user"] = current_user
        return self.render_to_response(context)
281

282

283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
class ProfilKontributorView(TemplateView):
    template_name = "profil.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated or not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(ProfilKontributorView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ProfilKontributorView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        current_user = self.request.user
        context["user"] = current_user
        return self.render_to_response(context)

301

302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(SuntingProfilView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(SuntingProfilView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
320
        context["form"] = SuntingProfilForm(instance=current_user)
321
322
323
324
325
326
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
327
        current_user = self.request.user
328
329
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
330
        if form.is_valid():
331
            current_user.default_profile_picture = True
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
332
            form.save()
333
334
335
336
337
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
338

339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
class SuntingProfilAdminView(TemplateView):
    template_name = "sunting_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_admin:
            raise PermissionDenied(request)
        return super(SuntingProfilAdminView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(SuntingProfilAdminView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

        context["form"] = SuntingProfilForm(instance=current_user)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_user = self.request.user
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
        if form.is_valid():
            current_user.default_profile_picture = True
            form.save()
            return HttpResponseRedirect("/profil-admin/")
        else:
            context = self.get_context_data(**kwargs)
373
374
            context["form"] = form
            return self.render_to_response(context)
375

376

377
378
379
380
381
382
383
class SuksesLoginKontributorView(TemplateView):
    template_name = "sukses_kontri.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(SuksesLoginKontributorView, self).dispatch(request, *args, **kwargs)
384

385
    def get_context_data(self, **kwargs):
386
387
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
388
389
390
391
392
393
394
395
396
397
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

        return self.render_to_response(context)

398

399
400
401
402
403
404
405
class SuksesLoginAdminView(TemplateView):
    template_name = "sukses_admin.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_admin:
            raise PermissionDenied(request)
        return super(SuksesLoginAdminView, self).dispatch(request, *args, **kwargs)
406

407
408
409
410
411
412
413
414
415
416
417
418
    def get_context_data(self, **kwargs):
        context = super(SuksesLoginAdminView, self).get_context_data(**kwargs)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        current_user = self.request.user
        context["user"] = current_user

        return self.render_to_response(context)

419
420
421
422
class CommentsView(TemplateView):
    template_name = "comments.html"

    def dispatch(self, request, *args, **kwargs):
423
        if not request.user.pk == kwargs["pk_user"] :
424
425
426
427
428
            raise PermissionDenied(request)
        return super(CommentsView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(CommentsView, self).get_context_data(**kwargs)
Saul Andre's avatar
Saul Andre committed
429
430
431
        user = get_object_or_404(User, pk=kwargs["pk_user"])
        users_materi = Materi.objects.filter(uploader=user)
        numb_of_comments = 0 
432
        qset_comments = Comment.objects.none()
Saul Andre's avatar
Saul Andre committed
433
434
435
        for materi in users_materi:
            materi_comments = Comment.objects.filter(materi=materi).count()
            numb_of_comments += materi_comments
436
437
            qset_comments |= Comment.objects.filter(materi=materi)
        context['comments'] = qset_comments.order_by('-timestamp')
Saul Andre's avatar
Saul Andre committed
438
439
        context["numb_of_comments"] = numb_of_comments
        context["numb_of_materi"] = users_materi.count()
440
441
442
443
444
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context=context)
445

446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

    def dispatch(self, request, *args, **kwargs):        
        if not request.user.is_contributor:
            raise PermissionDenied(request)
        return super(RevisiMateriView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(RevisiMateriView, self).get_context_data(**kwargs)
        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
        context["materi"] = current_materi
        context["revisi_form"] = UploadMateriForm(instance=current_materi)
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

    def post(self,request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
        form = UploadMateriForm(
            request.POST, request.FILES, instance=current_materi)
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.status = "REVISION"
            materi.save()
            kateg = form.cleaned_data['categories']
            for i in kateg:
                materi.categories.add(i)
            materi.save()
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

Samuel Dimas's avatar
Samuel Dimas committed
487
488
489
490
491
492
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

493
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
494
495
496
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

497
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
498

499
        template = loader.get_template("error-404.html")
Samuel Dimas's avatar
Samuel Dimas committed
500
        return HttpResponse(template.render(context, request))