Fakultas Ilmu Komputer UI

views.py 25.7 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.core.exceptions import PermissionDenied
from django.core.paginator import Paginator
from django.db.models import Q
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
26
27
from app.models import (
    Category,
    Comment,
    Materi,
    ReqMaterial,
    Rating,
)
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
        return self.render_to_response(context=context)
92

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

99

100
101
102
103
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

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

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

119
        return context
120

121

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

131

132

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

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

152

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


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

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

183

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


196
def add_rating_materi(request):
197
    if request.method == "POST" and request.user.is_authenticated:
198

199
200
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
201
202


203
204
205
206
        is_valid_params, materi_id, \
        rating_score, response, \
        status_code = MateriFieldValidationHelperService.\
            validate_materi_rating_params(materi_id,rating_score)
207

208
209
        if not is_valid_params:
            return JsonResponse(response, status=status_code)
210

211
212
213
        is_valid_rating, materi, \
        response, status_code = MateriFieldValidationHelperService.\
            validate_materi_rating(materi_id, request.user)
214

215
216
        if not is_valid_rating:
            return JsonResponse(response, status=status_code)
217
218

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


225

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

igor lestin sianipar's avatar
igor lestin sianipar committed
242

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

igor lestin sianipar's avatar
igor lestin sianipar committed
259

Selvy Fitriani's avatar
Selvy Fitriani committed
260
261
262
263
264
def delete_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
    materi.delete()
    return HttpResponseRedirect("/dashboard/")

igor lestin sianipar's avatar
igor lestin sianipar committed
265
class UploadMateriView(TemplateView):
266
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
267
268
269
270
271
272
    context = {}

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

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

292
293


igor lestin sianipar's avatar
igor lestin sianipar committed
294
    def get(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
295
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
296
            raise PermissionDenied(request)
297

igor lestin sianipar's avatar
igor lestin sianipar committed
298
        context = self.get_context_data(**kwargs)
299
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
300
        return self.render_to_response(context)
301

302

303

Samuel Dimas's avatar
Samuel Dimas committed
304

305
306
307
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
308

309
310
311
312
313
314
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


315
316
317
318
319
320
321
322
323
324
325
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):

326
        if "template" in self.request.GET:
327

328
329
330
            data_frame = pd.DataFrame(
                {"Title": [], "Author": [], "Publisher": [], "Categories": [], "Description": [],}
            )
331
332

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

                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):
349
350
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
351

352
        row, lines = excel.shape
353
        categories = Category.objects.all()
354

355
        field_length = {
356
357
358
            "title": 50,
            "author": 30,
            "publisher": 30,
359
360
361
362
363
364
        }

        message = None

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

366
            # Validate Categories
367
            message = UploadMateriService.validate_excel_categories(categories, excel, i, message)
368

369
            message = UploadMateriService.validate_excel_field_length(excel, field_length, i, message)
370
371
372

            if message != None:
                break
373

374
375
        if message != None:
            messages.error(request, message)
376
            return HttpResponseRedirect("/unggah_excel/")
377
378
379

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

382
        messages.success(request, "Materi berhasil diunggah")
383

384
        return HttpResponseRedirect("/unggah_excel/")
385
386


387
388


389
class DashboardKontributorView(TemplateView):
390
    template_name = "dashboard.html"
391
392
393
394
395
396
397

    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):
398
        context = super(DashboardKontributorView, self).get_context_data(**kwargs)
399
400
401
402
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
403
404
405
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
406
        return self.render_to_response(context)
407

408

409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
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)
426

427

428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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)

446

447
448
449
450
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
451
        if not request.user.is_authenticated or not request.user.is_contributor:
452
453
454
455
456
457
458
459
460
461
462
463
464
            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
465
        context["form"] = SuntingProfilForm(instance=current_user)
466
467
468
469
470
471
        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
472
        current_user = self.request.user
473

474
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
475
        if form.is_valid():
476
            current_user.default_profile_picture = True
477
478
479

            # Removing exifdata from profile picture on upload
            if request.FILES:
480
                EditProfileService.update_profile_picture(current_user, request)
481
            else:
482
                form.save()
483
484
485
486
487
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
488

igor lestin sianipar's avatar
igor lestin sianipar committed
489

490
491
492
493
494
495
496
497
498
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):
499
        context = super(SuntingProfilAdminView, self).get_context_data(**kwargs)
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
        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
516

517
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
518
519
        if form.is_valid():
            current_user.default_profile_picture = True
520
521
522

            # Removing exifdata from profile picture on upload
            if request.FILES:
523
                EditProfileService.update_profile_picture(current_user, request)
524
            else:
525
                form.save()
526
527
528
            return HttpResponseRedirect("/profil-admin/")
        else:
            context = self.get_context_data(**kwargs)
529
530
            context["form"] = form
            return self.render_to_response(context)
531

532

533
534
535
536
537
538
539
540
541
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):
542
        context = super(ReqMateriView, self).get_context_data(**kwargs)
543
544
545
546
547
548
549
        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):
550
        title = request.POST.get("title", None)
551
552
553
554
555
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

556

557
558
559
560
561
562
563
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)
564

565
    def get_context_data(self, **kwargs):
566
        context = super(SuksesLoginKontributorView, self).get_context_data(**kwargs)
567
568
569
570
571
572
573
574
575
576
        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)

577

578
579
580
581
582
583
584
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)
585

586
587
588
589
590
591
592
593
594
595
596
597
    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
598

599
600
601
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
602
603

    def dispatch(self, request, *args, **kwargs):
604
        if not request.user.is_authenticated:
605
            raise PermissionDenied(request)
606
        return super(PostsView, self).dispatch(request, *args, **kwargs)
607
608

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

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

615
        comments = Comment.objects.filter(materi__id__in=posts_data.keys()).order_by("-timestamp")
616
617
618
619
620
621
622

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

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

623
        return self.render_to_response(context=context)
624

625

626
627
628
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

629
    def dispatch(self, request, *args, **kwargs):
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
        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)

645
    def post(self, request, *args, **kwargs):
646
647
648
649
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
650
        form = UploadMateriForm(request.POST, request.FILES, instance=current_materi)
651
        if form.is_valid():
652
            RevisiMateriService.revisi_materi(form, request)
653
654
655
656
657
658
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

659

Samuel Dimas's avatar
Samuel Dimas committed
660
661
662
663
664
665
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

666
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
667
668
669
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

670
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
671

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


676
677
678
679
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
680
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
681
682
683
684
685
686
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
687
            DownloadHistoryService.init_data_authenticated_user(context, current_user)
688
        else:
689
            DownloadHistoryService.init_data_guest_user(context, request)
690
        return self.render_to_response(context)
691

692

693
694
695
696
697
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):
698
        GoogleDriveUploadService.upload_to_gdrive(file_path, materi.title)
699
700
701
    else:
        raise Http404("File tidak dapat ditemukan.")

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

Yaumi's avatar
Yaumi committed
704
class PasswordChangeView(PasswordChangeView):
Yaumi's avatar
Yaumi committed
705
    
Yaumi's avatar
Yaumi committed
706
707
    from_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
Yaumi's avatar
Yaumi committed
708

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