Fakultas Ilmu Komputer UI

views.py 24.4 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
from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
11
from django.db.models import Q, Avg
12
13
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
14
from django.shortcuts import get_object_or_404, redirect
15
from django.template import loader
16
from django.urls import reverse
17
from django.views import defaults
18
from django.views.generic import TemplateView
19

20
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm
21
22
23
24
25
from app.models import (
    Category,
    Comment,
    Materi,
    ReqMaterial,
26
    Rating, RatingContributor,
27
)
28
from authentication.models import User
29
30
31
from .services import DafterKatalogService, DetailMateriService, LikeDislikeService, MateriFieldValidationHelperService, \
    DownloadViewMateriHelperService, UploadMateriService, EditProfileService, RevisiMateriService, \
    DownloadHistoryService, GoogleDriveUploadService
32
33
34
35
from django.contrib.auth.views import PasswordChangeForm
from django.urls import reverse_lazy
from django.contrib.auth.views import PasswordChangeView
from django.shortcuts import render
36

37

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

41

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

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

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

58

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

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

68

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

72
73
74
75
76
77
78
79
    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)
80
81
82
83
84

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

85
        paginator = Paginator(materi_list, 15)
86
        page_number = request.GET.get("page")
87
88
        materi_list_by_page = paginator.get_page(page_number)
        context["materi_list"] = materi_list_by_page
89
        contributor = get_object_or_404(User, email=kwargs["email"])
90
        context["form_rating"] = RatingContributorForm(initial={"user": contributor})
91
92
93
        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()
94
        return self.render_to_response(context=context)
95

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

102

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

    def get_context_data(self, **kwargs):
107
108
109
110
        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"])
111
112
113
        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)
114
115
116
117

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

122
        return context
123

124

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

134

135

136
    def post(self, request, *args, **kwargs):
137
        commentText = request.POST.get("comment", None)
138
        if commentText == None or commentText == "":
139
140
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
141
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
142
            query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
143
            context["comment_data"] = query_set_for_comment
144
            return self.render_to_response(context=context)
145

146
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
147
        user_obj = request.user if request.user.is_authenticated else None
148
149
        if user_obj:
            comment = Comment.objects.create(
150
                comment=commentText, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
151
152
            )
            comment.save()
153
154
        return HttpResponseRedirect(request.path)

155

156
def toggle_like(request):
157
158
159
    if request.method == "POST":
        materi_id = request.POST.get("materi_id", None)
        session_id = request.POST.get("session_id", None)
160
161
        if materi_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
162
        return JsonResponse(LikeDislikeService.apply_like_materi(materi_id, session_id))
163
164
165
166
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method"})


167
def delete_comment(request, pk_materi, pk_comment):
168
169
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
170
    comment = get_object_or_404(Comment, pk=pk_comment)
171
    url = "/materi/" + str(pk_materi) + "/"
172
173
174
    comment.delete()
    return HttpResponseRedirect(url)

175
def toggle_like_comment(request):
176
    comment_id = 0
177
178
179
180
181
    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})
182
        return JsonResponse(LikeDislikeService.apply_comment_like(comment_id, session_id))
183
184
185
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})

186

187
def toggle_dislike_comment(request):
188
    comment_id = 0
189
190
191
192
193
    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})
194
        return JsonResponse(LikeDislikeService.apply_comment_dislike(comment_id, session_id))
195
196
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})
197
198


199
def add_rating_materi(request):
200
    if request.method == "POST" and request.user.is_authenticated:
201

202
203
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
204
205


206
207
208
209
        is_valid_params, materi_id, \
        rating_score, response, \
        status_code = MateriFieldValidationHelperService.\
            validate_materi_rating_params(materi_id,rating_score)
210

211
212
        if not is_valid_params:
            return JsonResponse(response, status=status_code)
213

214
215
216
        is_valid_rating, materi, \
        response, status_code = MateriFieldValidationHelperService.\
            validate_materi_rating(materi_id, request.user)
217

218
219
        if not is_valid_rating:
            return JsonResponse(response, status=status_code)
220
221

        Rating(materi=materi, user=request.user, score=rating_score).save()
222
223
224
        return JsonResponse(
            {"success": True, "msg": "Rating successfully created", "rating_score": rating_score}, status=201
        )
225
226
227
    return JsonResponse({"success": False, "msg": "Forbidden"}, status=403)


228

229
230
231
232
233
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):
234
235
236
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
237
238
239
                return DownloadViewMateriHelperService.build_materi_response(fh, file_path,
                                                                             materi, mimetype, request,
                                                                             HttpResponse(fh.read(), content_type=mimetype[0]))
240
241
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
242
243
244
    else:
        raise Http404("File tidak dapat ditemukan.")

igor lestin sianipar's avatar
igor lestin sianipar committed
245

246
247
248
249
250
251
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)
252
253
254
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
255
                DownloadViewMateriHelperService.build_view_materi_response(file_path, materi, response)
256
257
258
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
259
260
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
261

igor lestin sianipar's avatar
igor lestin sianipar committed
262

Selvy Fitriani's avatar
Selvy Fitriani committed
263
264
def delete_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
265
266
267
    if request.user.is_superuser or request.user.is_admin:
        materi.soft_delete()
        return HttpResponseRedirect("/administration/")
Selvy Fitriani's avatar
Selvy Fitriani committed
268
269
270
    materi.delete()
    return HttpResponseRedirect("/dashboard/")

igor lestin sianipar's avatar
igor lestin sianipar committed
271
class UploadMateriView(TemplateView):
272
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
273
274
275
276
277
278
    context = {}

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

Saul Andre's avatar
Saul Andre committed
279
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
280
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
281
            raise PermissionDenied(request)
282
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
283
284
285
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
286
            konten = form.cleaned_data["content"]
287
            if not UploadMateriService.validate_file_extension(konten, request):
288
                return HttpResponseRedirect("/unggah/")
289
            UploadMateriService.upload_materi(form, materi)
290
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
291
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
292
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
293
            context = self.get_context_data(**kwargs)
294
            context["form"] = form
295
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
296
297
            return self.render_to_response(context)

298
299


igor lestin sianipar's avatar
igor lestin sianipar committed
300
    def get(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
301
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
302
            raise PermissionDenied(request)
303

igor lestin sianipar's avatar
igor lestin sianipar committed
304
        context = self.get_context_data(**kwargs)
305
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
306
        return self.render_to_response(context)
307

308

309

Samuel Dimas's avatar
Samuel Dimas committed
310

311
312
313
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
314

315
316
317
318
319
320
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


321
322
323
324
325
326
327
328
329
330
331
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):

332
        if "template" in self.request.GET:
333

334
335
336
            data_frame = pd.DataFrame(
                {"Title": [], "Author": [], "Publisher": [], "Categories": [], "Description": [],}
            )
337
338

            with BytesIO() as b:
339
                writer = pd.ExcelWriter(b, engine="xlsxwriter")  # pylint: disable=abstract-class-instantiated
340
341
342
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
343
344
                    b.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
345
346
347
348
349
350
351
352
353
354

                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):
355
356
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
357

358
        row, lines = excel.shape
359
        categories = Category.objects.all()
360

361
        field_length = {
362
363
364
            "title": 50,
            "author": 30,
            "publisher": 30,
365
366
367
368
369
370
        }

        message = None

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

372
            # Validate Categories
373
            message = UploadMateriService.validate_excel_categories(categories, excel, i, message)
374

375
            message = UploadMateriService.validate_excel_field_length(excel, field_length, i, message)
376
377
378

            if message != None:
                break
379

380
381
        if message != None:
            messages.error(request, message)
382
            return HttpResponseRedirect("/unggah_excel/")
383
384
385

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

388
        messages.success(request, "Materi berhasil diunggah")
389

390
        return HttpResponseRedirect("/unggah_excel/")
391
392


393
394


395
class DashboardKontributorView(TemplateView):
396
    template_name = "dashboard.html"
397
398
399
400
401
402
403

    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):
404
        context = super(DashboardKontributorView, self).get_context_data(**kwargs)
405
406
407
408
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
409
410
411
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
412
        return self.render_to_response(context)
413

414

415
class ProfilView(TemplateView):
416
417
418
    template_name = "profil.html"

    def dispatch(self, request, *args, **kwargs):
419
        if not request.user.is_authenticated:
420
            raise PermissionDenied(request)
421
        return super(ProfilView, self).dispatch(request, *args, **kwargs)
422
423
424

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

429

430
431
432
433
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
434
        if not request.user.is_authenticated:
435
436
437
438
            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
439
        current_user = self.request.user
440
441
442
443
444
445
446
447
448
449
        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
450

451
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
452
453
        if form.is_valid():
            current_user.default_profile_picture = True
454
455
456

            # Removing exifdata from profile picture on upload
            if request.FILES:
457
                EditProfileService.update_profile_picture(current_user, request)
458
            else:
459
                form.save()
460
            return HttpResponseRedirect("/profil/")
461
462
        else:
            context = self.get_context_data(**kwargs)
463
464
            context["form"] = form
            return self.render_to_response(context)
465

466

467
468
469
470
471
472
473
474
475
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):
476
        context = super(ReqMateriView, self).get_context_data(**kwargs)
477
478
479
480
481
482
483
        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):
484
        title = request.POST.get("title", None)
485
486
487
488
489
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

490

491
492
493
494
495
496
497
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)
498

499
    def get_context_data(self, **kwargs):
500
        context = super(SuksesLoginKontributorView, self).get_context_data(**kwargs)
501
502
503
504
505
506
507
508
509
510
        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)

511

512
513
514
515
516
517
518
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)
519

520
521
522
523
524
525
526
527
528
529
530
531
    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
532

533
534
535
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
536
537

    def dispatch(self, request, *args, **kwargs):
538
        if not request.user.is_authenticated:
539
            raise PermissionDenied(request)
540
        return super(PostsView, self).dispatch(request, *args, **kwargs)
541
542

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

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

549
        comments = Comment.objects.filter(materi__id__in=posts_data.keys()).order_by("-timestamp")
550
551
552
553
554
555
556

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

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

557
        return self.render_to_response(context=context)
558

559

560
561
562
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

563
    def dispatch(self, request, *args, **kwargs):
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
        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)

579
    def post(self, request, *args, **kwargs):
580
581
582
583
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
584
        form = UploadMateriForm(request.POST, request.FILES, instance=current_materi)
585
        if form.is_valid():
586
            RevisiMateriService.revisi_materi(form, request)
587
588
589
590
591
592
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

593

Samuel Dimas's avatar
Samuel Dimas committed
594
595
596
597
598
599
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

600
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
601
602
603
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

604
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
605

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


610
611
612
613
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
614
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
615
616
617
618
619
620
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
621
            DownloadHistoryService.init_data_authenticated_user(context, current_user)
622
        else:
623
            DownloadHistoryService.init_data_guest_user(context, request)
624
        return self.render_to_response(context)
625

626

627
628
629
630
631
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):
632
        GoogleDriveUploadService.upload_to_gdrive(file_path, materi.title)
633
634
635
    else:
        raise Http404("File tidak dapat ditemukan.")

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

638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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
666
class PasswordChangeViews(PasswordChangeView):
Yaumi's avatar
Yaumi committed
667
    
Yaumi's avatar
Yaumi committed
668
669
    from_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
Yaumi's avatar
Yaumi committed
670

Yaumi's avatar
Yaumi committed
671
def password_success(request):
672
    return render(request, 'password_success.html', {})