Fakultas Ilmu Komputer UI

views.py 26.2 KB
Newer Older
1
2
import mimetypes
import os
3
from io import BytesIO
4

5
6
import django
import pandas as pd
7
from django.conf import settings
8
from django.contrib import messages
9
10
11
from django.contrib.auth.views import PasswordChangeForm
from django.contrib.auth.views import PasswordChangeView
from django.core.exceptions import PermissionDenied, FieldError
12
from django.core.paginator import Paginator
13
from django.db.models import Q, Avg
14
15
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
16
from django.shortcuts import get_object_or_404, redirect
17
from django.shortcuts import render
18
from django.template import loader
19
from django.urls import reverse
20
from django.urls import reverse_lazy
21
from django.views import defaults
22
from django.views.generic import TemplateView
23

24
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm
25
26
27
from app.models import (
    Category,
    Comment,
28
    Review,
29
30
    Materi,
    ReqMaterial,
31
    Rating, RatingContributor,
32
)
33
from authentication.models import User
34
35
36
37
from .services import DafterKatalogService, DetailMateriService, LikeDislikeService, MateriFieldValidationHelperService, \
    DownloadViewMateriHelperService, UploadMateriService, EditProfileService, RevisiMateriService, \
    DownloadHistoryService, GoogleDriveUploadService

38

39
def permission_denied(request, exception, template_name="error_403.html"):
40
41
    return defaults.permission_denied(request, exception, template_name)

42

43
class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
44
    paginate_by = 2
45
46
47
48
49
50
51
    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)
52
        context["kategori_list"] = Category.objects.all()
53

Mika dabelza abi's avatar
Mika dabelza abi committed
54
        lstMateri = Materi.objects.filter(status="APPROVE").order_by("date_modified")
Mika dabelza abi's avatar
Mika dabelza abi committed
55
56
        url = ""

57
        lstMateri, url = DafterKatalogService.apply_options(lstMateri, request, url)
Saul Andre's avatar
Saul Andre committed
58

59

Mika dabelza abi's avatar
Mika dabelza abi committed
60
        context["materi_list"] = lstMateri
Mika dabelza abi's avatar
Mika dabelza abi committed
61
        paginator = Paginator(context["materi_list"], 15)
62
        page_number = request.GET.get("page")
Mika dabelza abi's avatar
Mika dabelza abi committed
63
64
65
66
        page_obj = paginator.get_page(page_number)
        context["materi_list"] = page_obj

        context["url"] = url
67
68
        return self.render_to_response(context=context)

69

70
71
class KatalogPerKontributorView(TemplateView):
    template_name = "app/katalog_kontri.html"
72

73
74
75
76
77
78
79
80
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        contributor = get_object_or_404(User, email=kwargs["email"])
        context["contributor"] = contributor
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
81
82
83
84
85

        materi_list = Materi.objects.filter(status="APPROVE", uploader=context["contributor"]).order_by(
            "date_modified"
        )

86
        paginator = Paginator(materi_list, 15)
87
        page_number = request.GET.get("page")
88
89
        materi_list_by_page = paginator.get_page(page_number)
        context["materi_list"] = materi_list_by_page
90
        contributor = get_object_or_404(User, email=kwargs["email"])
91
        context["form_rating"] = RatingContributorForm(initial={"user": contributor})
92
93
94
        context["avg_rating"] = User.objects.filter(email=kwargs["email"]) \
            .annotate(avg_rating=Avg("ratingcontributor__score"))[0]
        context["count_rating"] = RatingContributor.objects.filter(user=contributor).count()
95
        return self.render_to_response(context=context)
96

97
98
99
100
    def post(self, request, *args, **kwargs):
        data = RatingContributorForm(request.POST)
        if data.is_valid():
            data.save()
101
102
        return redirect("katalog-per-kontributor", email=kwargs["email"])

103

104
105
106
107
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
108
109
110
111
        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"])
112
113
114
        DetailMateriService.init_context_data(context, materi, self.request.session)
        published_date = DetailMateriService.set_published_date(materi)
        DetailMateriService.init_citation_and_materi_rating(context, materi, published_date, self.request)
115
        DetailMateriService.init_materi_download_count(context, materi)
116
117
118
119

        if self.request.user.is_authenticated:
            materi_rating = Rating.objects.filter(materi=materi, user=self.request.user).first()
            if materi_rating is not None:
120
                context['materi_rating_score'] = materi_rating.score
121

122
        context['is_authenticated'] = self.request.user.is_authenticated
123

124
        return context
125

126

127
128
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
129
        query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
130
        query_set_for_review = Review.objects.filter(materi=context["materi_data"])
131
        has_disliked, has_liked = DetailMateriService.find_comment_like_dislike(query_set_for_comment, self.request.session)
132
        context["comment_data"] = query_set_for_comment
133
        context["review_data"] = query_set_for_review
134
135
        context["has_liked"] = has_liked
        context["has_disliked"] = has_disliked
136
137
        return self.render_to_response(context=context)

138

139

140
    def post(self, request, *args, **kwargs):
141
142
143
        comment_text = request.POST.get("comment", None)
        review_text  = request.POST.get("review", None)
        if ((comment_text == None or comment_text == "" )and (review_text == None or review_text == "")):
144
145
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
146
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
147
            query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
148
            context["comment_data"] = query_set_for_comment
149
150
            query_set_for_review = Review.objects.filter(materi=context["materi_data"])
            context["review_data"] = query_set_for_review
151
            return self.render_to_response(context=context)
152

153
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
154
        user_obj = request.user if request.user.is_authenticated else None
155
        if user_obj:
156
            if (comment_text != None ):
157
                comment = Comment.objects.create(
158
                    comment=comment_text, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
159
160
                )
                comment.save()
161
            elif (review_text != None):
162
                review = Review.objects.create(
163
                    review=review_text, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
164
165
                )
                review.save()
166
167
        return HttpResponseRedirect(request.path)

168

169
def toggle_like(request):
170
171
172
    if request.method == "POST":
        materi_id = request.POST.get("materi_id", None)
        session_id = request.POST.get("session_id", None)
173
174
        if materi_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
175
        return JsonResponse(LikeDislikeService.apply_like_materi(materi_id, session_id))
176
177
178
179
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method"})


180
def delete_comment(request, pk_materi, pk_comment):
181
182
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
183
    comment = get_object_or_404(Comment, pk=pk_comment)
184
    url = "/materi/" + str(pk_materi) + "/"
185
186
187
    comment.delete()
    return HttpResponseRedirect(url)

188
def toggle_like_comment(request):
189
    comment_id = 0
190
191
192
193
194
    if request.method == "POST":
        comment_id = request.POST.get("comment_id", None)
        session_id = request.POST.get("session_id", None)
        if comment_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter", "comment_id": comment_id})
195
        return JsonResponse(LikeDislikeService.apply_comment_like(comment_id, session_id))
196
197
198
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})

199

200
def toggle_dislike_comment(request):
201
    comment_id = 0
202
203
204
205
206
    if request.method == "POST":
        comment_id = request.POST.get("comment_id", None)
        session_id = request.POST.get("session_id", None)
        if comment_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter", "comment_id": comment_id})
207
        return JsonResponse(LikeDislikeService.apply_comment_dislike(comment_id, session_id))
208
209
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})
210
211


212
def add_rating_materi(request):
213
    if request.method == "POST" and request.user.is_authenticated:
214

215
216
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
217
218


219
220
221
222
        is_valid_params, materi_id, \
        rating_score, response, \
        status_code = MateriFieldValidationHelperService.\
            validate_materi_rating_params(materi_id,rating_score)
223

224
225
        if not is_valid_params:
            return JsonResponse(response, status=status_code)
226

227
228
229
        is_valid_rating, materi, \
        response, status_code = MateriFieldValidationHelperService.\
            validate_materi_rating(materi_id, request.user)
230

231
232
        if not is_valid_rating:
            return JsonResponse(response, status=status_code)
233
234

        Rating(materi=materi, user=request.user, score=rating_score).save()
235
236
237
        return JsonResponse(
            {"success": True, "msg": "Rating successfully created", "rating_score": rating_score}, status=201
        )
238
239
240
    return JsonResponse({"success": False, "msg": "Forbidden"}, status=403)


241

242
243
244
245
246
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):
247
248
249
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
250
251
252
                return DownloadViewMateriHelperService.build_materi_response(fh, file_path,
                                                                             materi, mimetype, request,
                                                                             HttpResponse(fh.read(), content_type=mimetype[0]))
253
254
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
255
256
257
    else:
        raise Http404("File tidak dapat ditemukan.")

igor lestin sianipar's avatar
igor lestin sianipar committed
258

259
260
261
262
263
264
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)
265
266
267
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
268
                DownloadViewMateriHelperService.build_view_materi_response(file_path, materi, response)
269
270
271
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
272
273
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
274

igor lestin sianipar's avatar
igor lestin sianipar committed
275

Selvy Fitriani's avatar
Selvy Fitriani committed
276
277
def delete_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
278
279
280
    if request.user.is_superuser or request.user.is_admin:
        materi.soft_delete()
        return HttpResponseRedirect("/administration/")
Selvy Fitriani's avatar
Selvy Fitriani committed
281
282
283
    materi.delete()
    return HttpResponseRedirect("/dashboard/")

igor lestin sianipar's avatar
igor lestin sianipar committed
284
class UploadMateriView(TemplateView):
285
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
286
287
288
289
290
291
    context = {}

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

Saul Andre's avatar
Saul Andre committed
292
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
293
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
294
            raise PermissionDenied(request)
295
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
296
297
298
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
299
            konten = form.cleaned_data["content"]
300
301
            yt_url_id = form.cleaned_data['yt_video_id']
            if not UploadMateriService.validate_file_extension(konten, request, yt_url_id):
302
                return HttpResponseRedirect("/unggah/")
303
            UploadMateriService.upload_materi(form, materi)
304
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
305
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
306
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
307
            context = self.get_context_data(**kwargs)
308
            context["form"] = form
309
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
310
311
            return self.render_to_response(context)

312
313


igor lestin sianipar's avatar
igor lestin sianipar committed
314
    def get(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
315
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
316
            raise PermissionDenied(request)
317

igor lestin sianipar's avatar
igor lestin sianipar committed
318
        context = self.get_context_data(**kwargs)
319
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
320
        return self.render_to_response(context)
321

322

323
324
325
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
326

327
328
329
330
331
332
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


333
334
335
336
337
338
339
340
341
342
343
class UploadMateriExcelView(TemplateView):
    template_name = "unggah_excel.html"
    context = {}

    def get_template_names(self):
        if self.request.path == "/unggah_excel/":
            template_name = "unggah_excel.html"
        return template_name

    def get(self, request, *args, **kwargs):

344
        if "template" in self.request.GET:
345

346
347
348
            data_frame = pd.DataFrame(
                {"Title": [], "Author": [], "Publisher": [], "Categories": [], "Description": [],}
            )
349
350

            with BytesIO() as b:
351
                writer = pd.ExcelWriter(b, engine="xlsxwriter")  # pylint: disable=abstract-class-instantiated
352
353
354
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
355
356
                    b.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
357
358
359
360
361
362
363
364
365
366

                response["Content-Disposition"] = "attachment; filename=template.xlsx"

                return response

        else:
            context = self.get_context_data(**kwargs)
            return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
367
368
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
369

370
        row, lines = excel.shape
371
        categories = Category.objects.all()
372

373
        field_length = {
374
375
376
            "title": 50,
            "author": 30,
            "publisher": 30,
377
378
379
380
381
382
        }

        message = None

        # First pass, validate input
        for i in range(row):
383

384
            # Validate Categories
385
            message = UploadMateriService.validate_excel_categories(categories, excel, i, message)
386

387
            message = UploadMateriService.validate_excel_field_length(excel, field_length, i, message)
388
389
390

            if message != None:
                break
391

392
393
        if message != None:
            messages.error(request, message)
394
            return HttpResponseRedirect("/unggah_excel/")
395
396
397

        # Second pass, save data
        with django.db.transaction.atomic():
398
            UploadMateriService.upload_materi_excel(categories, excel, request, row)
399

400
        messages.success(request, "Materi berhasil diunggah")
401

402
        return HttpResponseRedirect("/unggah_excel/")
403
404


405
406


407
class DashboardKontributorView(TemplateView):
408
    template_name = "dashboard.html"
409
410
411
412
413
414
415

    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):
416
        context = super(DashboardKontributorView, self).get_context_data(**kwargs)
417
418
419
420
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
421
422
423
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
424
        return self.render_to_response(context)
425

426

427
class ProfilView(TemplateView):
428
429
430
    template_name = "profil.html"

    def dispatch(self, request, *args, **kwargs):
431
        if not request.user.is_authenticated:
432
            raise PermissionDenied(request)
433
        return super(ProfilView, self).dispatch(request, *args, **kwargs)
434
435
436

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

441

442
443
444
445
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
446
        if not request.user.is_authenticated:
447
448
449
450
            raise PermissionDenied(request)
        return super(SuntingProfilView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
451
        current_user = self.request.user
452
453
454
455
456
457
458
459
460
461
        context = self.get_context_data(**kwargs)
        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
462

463
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
464
465
        if form.is_valid():
            current_user.default_profile_picture = True
466
467
468

            # Removing exifdata from profile picture on upload
            if request.FILES:
469
                EditProfileService.update_profile_picture(current_user, request)
470
            else:
471
                form.save()
472
            return HttpResponseRedirect("/profil/")
473
474
        else:
            context = self.get_context_data(**kwargs)
475
476
            context["form"] = form
            return self.render_to_response(context)
477

478

479
480
481
482
483
484
485
486
487
class ReqMateriView(TemplateView):
    template_name = "req_materi.html"

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            return HttpResponseRedirect("/login/")
        return super(ReqMateriView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
488
        context = super(ReqMateriView, self).get_context_data(**kwargs)
489
490
491
492
493
494
495
        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):
496
        title = request.POST.get("title", None)
497
498
499
500
501
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

502

503
504
505
506
507
508
509
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)
510

511
    def get_context_data(self, **kwargs):
512
        context = super(SuksesLoginKontributorView, self).get_context_data(**kwargs)
513
514
515
516
517
518
519
520
521
522
        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)

523

524
525
526
527
528
529
530
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)
531

532
533
534
535
536
537
538
539
540
541
542
543
    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)

igor lestin sianipar's avatar
igor lestin sianipar committed
544

545
546
547
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
548
549

    def dispatch(self, request, *args, **kwargs):
550
        if not request.user.is_authenticated:
551
            raise PermissionDenied(request)
552
        return super(PostsView, self).dispatch(request, *args, **kwargs)
553
554

    def get(self, request, *args, **kwargs):
555
556
557
558
        context = super().get_context_data(**kwargs)
        user = self.request.user

        posts = Materi.objects.filter(uploader=user).order_by("-date_created")
559
        posts_data = {post.id: {"data": post, "comments": []} for post in posts}
560

561
        comments = Comment.objects.filter(materi__id__in=posts_data.keys()).order_by("-timestamp")
562
563
564
565
566
567
568

        for comment in comments:
            posts_data[comment.materi.id]["comments"].append(comment)

        context["user"] = user
        context["posts"] = posts_data

569
        return self.render_to_response(context=context)
570

571

572
573
574
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

575
    def dispatch(self, request, *args, **kwargs):
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
        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)

591
    def post(self, request, *args, **kwargs):
592
593
594
595
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
596
        form = UploadMateriForm(request.POST, request.FILES, instance=current_materi)
597
        if form.is_valid():
598
            RevisiMateriService.revisi_materi(form, request)
599
600
601
602
603
604
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

605

Samuel Dimas's avatar
Samuel Dimas committed
606
607
608
609
610
611
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

612
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
613
614
615
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

616
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
617

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


622
623
624
625
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
626
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
627
628
629
630
631
632
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
633
            DownloadHistoryService.init_data_authenticated_user(context, current_user)
634
        else:
635
            DownloadHistoryService.init_data_guest_user(context, request)
636
        return self.render_to_response(context)
637

638

639
640
641
642
643
def save_to_gdrive(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):
644
        GoogleDriveUploadService.upload_to_gdrive(file_path, materi.title)
645
646
647
    else:
        raise Http404("File tidak dapat ditemukan.")

Yaumi's avatar
Yaumi committed
648
649
    return HttpResponseRedirect(reverse('detail-materi', kwargs={'pk': pk}))

650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
class MateriFavorite(TemplateView):

    template_name = "user_favorite_materi.html"

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

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

        materi = Materi.objects.filter(like=True)
        likes_data = { mat.id: { "data": mat, "comments": [] } for mat in materi }

        comments = Comment.objects \
            .filter(materi__id__in=likes_data.keys()) \
            .order_by("-timestamp")

        for comment in comments:
            likes_data[comment.materi.id]["comments"].append(comment)

        context["user"] = user
        context["likes"] = likes_data

        return self.render_to_response(context=context)

Yaumi's avatar
Yaumi committed
678
class PasswordChangeViews(PasswordChangeView):
679

Yaumi's avatar
Yaumi committed
680
681
    from_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
Yaumi's avatar
Yaumi committed
682

Yaumi's avatar
Yaumi committed
683
def password_success(request):
684
    return render(request, 'password_success.html', {})
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708


def see_given_rating(request):
    if request.user.is_authenticated:
        order_by_key = request.GET.get('order_by_key', 'timestamp')

        if request.GET.get('order', '').lower() == 'asc':
            order_by = 'asc'
            query_order = ''
        else:
            order_by = 'dsc'
            query_order = '-'

        try:
            if order_by_key[0] == '-':
                order_by_key = order_by_key[1:]
            rating_list = Rating.objects.filter(user=request.user).order_by(query_order + order_by_key)
        except FieldError:
            order_by_key = 'timestamp'
            rating_list = Rating.objects.filter(user=request.user).order_by(query_order + order_by_key)

        return render(request, 'given-rating.html',
                      context={'rating_list': rating_list, 'order_by_key': order_by_key, 'order_by': order_by})
    return permission_denied(request, exception=None)