Fakultas Ilmu Komputer UI

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

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

26
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm
27
28
29
from app.models import (
    Category,
    Comment,
30
    Review,
31
32
    Materi,
    ReqMaterial,
33
    Rating, RatingContributor,
insan ramadhan's avatar
insan ramadhan committed
34
    SubmitVisitor
35
)
36
from authentication.models import User
37
38
39
40
from .services import DafterKatalogService, DetailMateriService, LikeDislikeService, MateriFieldValidationHelperService, \
    DownloadViewMateriHelperService, UploadMateriService, EditProfileService, RevisiMateriService, \
    DownloadHistoryService, GoogleDriveUploadService

41

42
def permission_denied(request, exception, template_name="error_403.html"):
43
44
    return defaults.permission_denied(request, exception, template_name)

45

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

Mika dabelza abi's avatar
Mika dabelza abi committed
57
        lstMateri = Materi.objects.filter(status="APPROVE").order_by("date_modified")
Mika dabelza abi's avatar
Mika dabelza abi committed
58
59
        url = ""

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

62

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

        context["url"] = url
70
71
        return self.render_to_response(context=context)

72

73
74
class KatalogPerKontributorView(TemplateView):
    template_name = "app/katalog_kontri.html"
75

76
77
78
79
80
81
82
83
    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)
84
85
86
87
88

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

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

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

106

107
108
109
110
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
111
112
113
114
        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"])
115
116
117
        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)
118
        DetailMateriService.init_materi_download_count(context, materi)
119
120
121
122

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

125
        context['is_authenticated'] = self.request.user.is_authenticated
126

127
        return context
128

129

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

141

142

143
    def post(self, request, *args, **kwargs):
144
145
146
        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 == "")):
147
148
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
149
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
150
            query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
151
            context["comment_data"] = query_set_for_comment
152
153
            query_set_for_review = Review.objects.filter(materi=context["materi_data"])
            context["review_data"] = query_set_for_review
154
            return self.render_to_response(context=context)
155

156
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
157
        user_obj = request.user if request.user.is_authenticated else None
158
        if user_obj:
159
            if (comment_text != None ):
160
                comment = Comment.objects.create(
161
                    comment=comment_text, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
162
163
                )
                comment.save()
164
165
166
167
168
169
170
171
172
173
174
175
176
                materi_uploader = materi.uploader
                if materi_uploader.is_subscribing_to_material_comments and user_obj.email != materi_uploader.email:
                    email_content =  f'User dengan email {user_obj.email} ' + \
                        f'menambahkan komentar pada materi Anda dengan judul "{materi.title}".' + \
                        f'\nKomentar: "{comment.comment}".\n' + \
                        f'Silahkan akses halaman detail materi untuk berinteraksi lebih lanjut.'
                    send_mail(
                        subject = 'DIGIPUS: Komentar Baru pada Materi Anda',
                        message = email_content,
                        from_email = getattr(settings, 'EMAIL_HOST_USER'),
                        recipient_list = [materi_uploader.email,],
                        fail_silently = False,
                    ) 
177
            elif (review_text != None):
178
                review = Review.objects.create(
179
                    review=review_text, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
180
181
                )
                review.save()
182
183
        return HttpResponseRedirect(request.path)

184

185
def toggle_like(request):
186
187
188
    if request.method == "POST":
        materi_id = request.POST.get("materi_id", None)
        session_id = request.POST.get("session_id", None)
189
190
        if materi_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
191
        return JsonResponse(LikeDislikeService.apply_like_materi(materi_id, session_id))
192
193
194
195
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method"})


196
def delete_comment(request, pk_materi, pk_comment):
197
198
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
199
    comment = get_object_or_404(Comment, pk=pk_comment)
200
    url = "/materi/" + str(pk_materi) + "/"
201
202
203
    comment.delete()
    return HttpResponseRedirect(url)

204
def toggle_like_comment(request):
205
    comment_id = 0
206
207
208
209
210
    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})
211
        return JsonResponse(LikeDislikeService.apply_comment_like(comment_id, session_id))
212
213
214
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})

215

216
def toggle_dislike_comment(request):
217
    comment_id = 0
218
219
220
221
222
    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})
223
        return JsonResponse(LikeDislikeService.apply_comment_dislike(comment_id, session_id))
224
225
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})
226
227


228
def add_rating_materi(request):
229
    if request.method == "POST" and request.user.is_authenticated:
230

231
232
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
233
234


235
236
237
238
        is_valid_params, materi_id, \
        rating_score, response, \
        status_code = MateriFieldValidationHelperService.\
            validate_materi_rating_params(materi_id,rating_score)
239

240
241
        if not is_valid_params:
            return JsonResponse(response, status=status_code)
242

243
244
245
        is_valid_rating, materi, \
        response, status_code = MateriFieldValidationHelperService.\
            validate_materi_rating(materi_id, request.user)
246

247
248
        if not is_valid_rating:
            return JsonResponse(response, status=status_code)
249
250

        Rating(materi=materi, user=request.user, score=rating_score).save()
251
252
253
        return JsonResponse(
            {"success": True, "msg": "Rating successfully created", "rating_score": rating_score}, status=201
        )
254
255
256
    return JsonResponse({"success": False, "msg": "Forbidden"}, status=403)


257

258
259
260
261
262
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):
263
264
265
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
266
267
268
                return DownloadViewMateriHelperService.build_materi_response(fh, file_path,
                                                                             materi, mimetype, request,
                                                                             HttpResponse(fh.read(), content_type=mimetype[0]))
269
270
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
271
272
273
    else:
        raise Http404("File tidak dapat ditemukan.")

igor lestin sianipar's avatar
igor lestin sianipar committed
274

275
276
277
278
279
280
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)
281
282
283
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
284
                DownloadViewMateriHelperService.build_view_materi_response(file_path, materi, response)
285
286
287
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
288
289
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
290

igor lestin sianipar's avatar
igor lestin sianipar committed
291

Selvy Fitriani's avatar
Selvy Fitriani committed
292
293
def delete_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
294
295
296
    if request.user.is_superuser or request.user.is_admin:
        materi.soft_delete()
        return HttpResponseRedirect("/administration/")
Selvy Fitriani's avatar
Selvy Fitriani committed
297
298
299
    materi.delete()
    return HttpResponseRedirect("/dashboard/")

igor lestin sianipar's avatar
igor lestin sianipar committed
300
class UploadMateriView(TemplateView):
301
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
302
303
304
305
306
307
    context = {}

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

Saul Andre's avatar
Saul Andre committed
308
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
309
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
310
            raise PermissionDenied(request)
311
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
312
313
314
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
315
            konten = form.cleaned_data["content"]
316
317
            yt_url_id = form.cleaned_data['yt_video_id']
            if not UploadMateriService.validate_file_extension(konten, request, yt_url_id):
318
                return HttpResponseRedirect("/unggah/")
319
            UploadMateriService.upload_materi(form, materi)
320
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
321
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
322
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
323
            context = self.get_context_data(**kwargs)
324
            context["form"] = form
325
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
326
327
            return self.render_to_response(context)

328
329


igor lestin sianipar's avatar
igor lestin sianipar committed
330
    def get(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
331
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
332
            raise PermissionDenied(request)
333

igor lestin sianipar's avatar
igor lestin sianipar committed
334
        context = self.get_context_data(**kwargs)
335
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
336
        return self.render_to_response(context)
337

338

339
340
341
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
342

343
344
345
346
347
348
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


349
350
351
352
353
354
355
356
357
358
359
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):

360
        if "template" in self.request.GET:
361

362
363
364
            data_frame = pd.DataFrame(
                {"Title": [], "Author": [], "Publisher": [], "Categories": [], "Description": [],}
            )
365
366

            with BytesIO() as b:
367
                writer = pd.ExcelWriter(b, engine="xlsxwriter")  # pylint: disable=abstract-class-instantiated
368
369
370
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
371
372
                    b.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
373
374
375
376
377
378
379
380
381
382

                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):
383
384
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
385

386
        row, lines = excel.shape
387
        categories = Category.objects.all()
388

389
        field_length = {
390
391
392
            "title": 50,
            "author": 30,
            "publisher": 30,
393
394
395
396
397
398
        }

        message = None

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

400
            # Validate Categories
401
            message = UploadMateriService.validate_excel_categories(categories, excel, i, message)
402

403
            message = UploadMateriService.validate_excel_field_length(excel, field_length, i, message)
404
405
406

            if message != None:
                break
407

408
409
        if message != None:
            messages.error(request, message)
410
            return HttpResponseRedirect("/unggah_excel/")
411
412
413

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

416
        messages.success(request, "Materi berhasil diunggah")
417

418
        return HttpResponseRedirect("/unggah_excel/")
419
420


421
422


423
class DashboardKontributorView(TemplateView):
424
    template_name = "dashboard.html"
425
426
427
428
429
430
431

    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):
432
        context = super(DashboardKontributorView, self).get_context_data(**kwargs)
433
434
435
436
        return context

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

442

443
class ProfilView(TemplateView):
444
445
446
    template_name = "profil.html"

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

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

457

458
459
460
461
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
462
        if not request.user.is_authenticated:
463
464
465
466
            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
467
        current_user = self.request.user
468
469
470
471
472
473
474
475
476
477
        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
478

479
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
480
481
        if form.is_valid():
            current_user.default_profile_picture = True
482
483
484

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

494

495
496
497
498
499
500
501
502
503
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):
504
        context = super(ReqMateriView, self).get_context_data(**kwargs)
505
506
507
508
509
510
511
        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):
512
        title = request.POST.get("title", None)
513
514
515
516
517
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

518

519
520
521
522
523
524
525
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)
526

527
    def get_context_data(self, **kwargs):
528
        context = super(SuksesLoginKontributorView, self).get_context_data(**kwargs)
529
530
531
532
533
534
535
536
537
538
        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)

539

540
541
542
543
544
545
546
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)
547

548
549
550
551
552
553
554
555
556
557
558
559
    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
560

561
562
563
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
564
565

    def dispatch(self, request, *args, **kwargs):
566
        if not request.user.is_authenticated:
567
            raise PermissionDenied(request)
568
        return super(PostsView, self).dispatch(request, *args, **kwargs)
569
570

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

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

577
        comments = Comment.objects.filter(materi__id__in=posts_data.keys()).order_by("-timestamp")
578
579
580
581
582
583
584

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

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

585
        return self.render_to_response(context=context)
586

587

588
589
590
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

591
    def dispatch(self, request, *args, **kwargs):
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
        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)

607
    def post(self, request, *args, **kwargs):
608
609
610
611
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
612
        form = UploadMateriForm(request.POST, request.FILES, instance=current_materi)
613
        if form.is_valid():
614
            RevisiMateriService.revisi_materi(form, request)
615
616
617
618
619
620
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

621

Samuel Dimas's avatar
Samuel Dimas committed
622
623
624
625
626
627
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

628
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
629
630
631
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

632
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
633

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


638
639
640
641
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
642
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
643
644
645
646
647
648
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
649
            DownloadHistoryService.init_data_authenticated_user(context, current_user)
650
        else:
651
            DownloadHistoryService.init_data_guest_user(context, request)
652
        return self.render_to_response(context)
653

654

655
656
657
658
659
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):
660
        GoogleDriveUploadService.upload_to_gdrive(file_path, materi.title)
661
662
663
    else:
        raise Http404("File tidak dapat ditemukan.")

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

666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
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
694
class PasswordChangeViews(PasswordChangeView):
695

Yaumi's avatar
Yaumi committed
696
697
    from_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
Yaumi's avatar
Yaumi committed
698

Yaumi's avatar
Yaumi committed
699
def password_success(request):
700
    return render(request, 'password_success.html', {})
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724


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)
insan ramadhan's avatar
insan ramadhan committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749

class SubmitVisitorView(TemplateView):
    template_name = "submit_visitor.html"

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

    def get_context_data(self, **kwargs):
        context = super(SubmitVisitorView, self).get_context_data(**kwargs)
        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):
        title = request.POST.get("title", None)
        email = request.POST.get("email", None)
        user_id = request.POST.get("user_id", None)
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        SubmitVisitor(msg=title, user_id=user_id, email=email).save()
        return JsonResponse({"success": True, "msg": "Buku tamu berhasil ditambahkan"})