Fakultas Ilmu Komputer UI

views.py 35.6 KB
Newer Older
1
2
import mimetypes
import os
3
from io import BytesIO
4
from register.services import MailService
5

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

27
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm, GuestBookForm
28
29
30
from app.models import (
    Category,
    Comment,
31
    Review,
32
    Materi,
Yusuf T Ardho's avatar
Yusuf T Ardho committed
33
    LaporanMateri,
34
    ReqMaterial,
35
    Rating, RatingContributor,
Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
36
    SubmitVisitor,
37
    GuestBook,
38
    ReadLater,
39
    NotifikasiKontributor,
40
    AdminNotification
41
)
42
from authentication.models import User
43
44
from .services import DafterKatalogService, DetailMateriService, LikeDislikeService, MateriFieldValidationHelperService, \
    DownloadViewMateriHelperService, UploadMateriService, EditProfileService, RevisiMateriService, \
Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
45
    DownloadHistoryService, GoogleDriveUploadService, ReadLaterService
46

47
48
49
50
51
52
53
MISSING_PARAMETER_MESSAGE = "Missing parameter"
UNSUPPORTED_MESSAGE = "Unsuported method"
FILE_NOT_FOUND_MESSAGE = "File tidak dapat ditemukan."
UNGGAH_HTML = "unggah.html"
UNGGAH_URL = "/unggah/"
UNGGAH_EXCEL_URL = "/unggah_excel/"
LOGIN_URL = "/login/"
54

55

56
def permission_denied(request, exception, template_name="error_403.html"):
57
58
    return defaults.permission_denied(request, exception, template_name)

59

60
class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
61
    paginate_by = 2
62
63
64
65
66
67
68
    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)
69
        context["kategori_list"] = Category.objects.all()
70

71
72
        lst_materi = Materi.objects.filter(
            status="APPROVE").order_by("date_modified")
Mika dabelza abi's avatar
Mika dabelza abi committed
73
74
        url = ""

75
76
        lst_materi, url = DafterKatalogService.apply_options(
            lst_materi, request, url)
77

78
        context["materi_list"] = lst_materi
Mika dabelza abi's avatar
Mika dabelza abi committed
79
        paginator = Paginator(context["materi_list"], 15)
80
        page_number = request.GET.get("page")
Mika dabelza abi's avatar
Mika dabelza abi committed
81
82
83
84
        page_obj = paginator.get_page(page_number)
        context["materi_list"] = page_obj

        context["url"] = url
85
86
        return self.render_to_response(context=context)

87

88
89
class KatalogPerKontributorView(TemplateView):
    template_name = "app/katalog_kontri.html"
90

91
92
93
94
95
96
97
98
    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)
99
100
101
102
103

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

104
        paginator = Paginator(materi_list, 15)
105
        page_number = request.GET.get("page")
106
107
        materi_list_by_page = paginator.get_page(page_number)
        context["materi_list"] = materi_list_by_page
108
109
110
        contributor = context["contributor"]
        context["form_rating"] = RatingContributorForm(initial={
            "contributor": contributor,
111
            "user": request.user
112
        })
113
        context["avg_rating"] = User.objects.filter(email=kwargs["email"]) \
114
            .annotate(avg_rating=Avg("contributor__score"))[0]
115
116
        context["count_rating"] = RatingContributor.objects.filter(
            contributor=contributor).count()
117
118

        if request.user.is_authenticated:
119
120
            has_rated = RatingContributor.objects.filter(
                user=request.user, contributor=contributor).exists()
121
122
            context["has_rated"] = has_rated

123
        return self.render_to_response(context=context)
124

125
    def post(self, request, *args, **kwargs):
126
127
128
129
130
131
132
133
        context = self.get_context_data(**kwargs)
        if not request.user.is_authenticated:
            raise PermissionDenied(request)

        is_delete = request.POST.get('delete', None)
        is_update = request.POST.get('update', None)
        if is_delete:
            rating_contributor = get_object_or_404(
134
                RatingContributor,
135
136
137
138
139
140
141
142
143
144
                user=request.user,
                contributor=context["contributor"]
            )
            rating_contributor.delete()
        elif is_update:
            score = request.POST.get('score', None)
            rating = RatingContributor.objects.filter(
                user=request.user,
                contributor=context["contributor"]
            ).first()
145

146
147
148
149
150
151
152
            if rating and score:
                rating.score = int(score)
                rating.save()
        else:
            data = RatingContributorForm(request.POST)
            if data.is_valid():
                data.save()
153

154
155
        return redirect("katalog-per-kontributor", email=kwargs["email"])

156

157
158
159
160
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
161
162
163
164
        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"])
165
166
        DetailMateriService.init_context_data(
            context, materi, self.request.session)
167
        published_date = DetailMateriService.set_published_date(materi)
168
169
        DetailMateriService.init_citation_and_materi_rating(
            context, materi, published_date, self.request)
170
        DetailMateriService.init_materi_download_count(context, materi)
171
172

        if self.request.user.is_authenticated:
173
174
            materi_rating = Rating.objects.filter(
                materi=materi, user=self.request.user).first()
175
            if materi_rating is not None:
176
                context['materi_rating_score'] = materi_rating.score
177

178
179
            materi_read_later = ReadLater.objects.filter(
                materi=materi, user=self.request.user).first()
Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
180
181
182
183
184
            if materi_read_later is not None:
                context['is_in_read_later_list'] = True
            else:
                context['is_in_read_later_list'] = False

185
        context['is_authenticated'] = self.request.user.is_authenticated
186

187
        return context
188
189
190

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
191
192
193
194
195
196
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
        query_set_for_review = Review.objects.filter(
            materi=context["materi_data"])
        has_disliked, has_liked = DetailMateriService.find_comment_like_dislike(
            query_set_for_comment, self.request.session)
197
        context["comment_data"] = query_set_for_comment
198
        context["review_data"] = query_set_for_review
199
200
        context["has_liked_comment"] = has_liked
        context["has_disliked_comment"] = has_disliked
201
202
203
        if request.user.is_authenticated and request.user.is_contributor:
            opened_notif = NotifikasiKontributor.objects.filter(user=request.user, materi=context["materi_data"])
            opened_notif.delete()
204
205
        return self.render_to_response(context=context)

206
    def post(self, request, *args, **kwargs):
207
        comment_text = request.POST.get("comment", None)
208
        review_text = request.POST.get("review", None)
Yusuf T Ardho's avatar
Yusuf T Ardho committed
209
        report_text = request.POST.get("report", None)
210
211
212
        if ((comment_text == None or comment_text == "") and
            (review_text == None or review_text == "") and
                (report_text == None or report_text == "")):
213
214
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
215
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
216
217
            query_set_for_comment = Comment.objects.filter(
                materi=context["materi_data"])
218
            context["comment_data"] = query_set_for_comment
219
220
            query_set_for_review = Review.objects.filter(
                materi=context["materi_data"])
221
            context["review_data"] = query_set_for_review
222
            return self.render_to_response(context=context)
223

224
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
225
        user_obj = request.user if request.user.is_authenticated else None
226
        if user_obj:
227
            if (comment_text != None):
228
                comment = Comment.objects.create(
229
                    comment=comment_text, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
230
231
                )
                comment.save()
232
233
                materi_uploader = materi.uploader
                if materi_uploader.is_subscribing_to_material_comments and user_obj.email != materi_uploader.email:
234
                    email_content = f'User dengan email {user_obj.email} ' + \
235
236
237
                        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.'
238
239

                    MailService.send(
240
241
242
243
244
                        subject='DIGIPUS: Komentar Baru pada Materi Anda',
                        message=email_content,
                        from_email=getattr(settings, 'EMAIL_HOST_USER'),
                        recipient_list=[materi_uploader.email, ],
                    )
245
            elif (review_text != None):
246
                review = Review.objects.create(
247
                    review=review_text, username=DetailMateriService.get_user_name(request), materi=materi, user=user_obj
248
249
                )
                review.save()
Yusuf T Ardho's avatar
Yusuf T Ardho committed
250
251
252
253
254
            elif (report_text != None):
                laporan_materi = LaporanMateri.objects.create(
                    materi=materi, laporan=report_text, user=user_obj
                )
                laporan_materi.save()
255
256
        return HttpResponseRedirect(request.path)

257

258
def toggle_like(request):
259
260
261
    if request.method == "POST":
        materi_id = request.POST.get("materi_id", None)
        session_id = request.POST.get("session_id", None)
262
        if materi_id is None or session_id is None:
263
            return JsonResponse({"success": False, "msg": MISSING_PARAMETER_MESSAGE})
264
        return JsonResponse(LikeDislikeService.apply_like_materi(materi_id, session_id))
265
    else:
266
        return JsonResponse({"success": False, "msg": UNSUPPORTED_MESSAGE})
267
268


269
def delete_comment(request, pk_materi, pk_comment):
270
271
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
272
    comment = get_object_or_404(Comment, pk=pk_comment)
273
    url = "/materi/" + str(pk_materi) + "/"
274
275
276
    comment.delete()
    return HttpResponseRedirect(url)

277
278
279
280
281
282
283
284
def delete_review(request, pk_materi, pk_review):
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
    review = get_object_or_404(Review, pk=pk_review)
    url_materi = "/materi/" + str(pk_materi) + "/"
    review.delete()
    return HttpResponseRedirect(url_materi)

285
def toggle_like_comment(request):
286
    comment_id = 0
287
288
289
290
    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:
291
            return JsonResponse({"success": False, "msg": MISSING_PARAMETER_MESSAGE, "comment_id": comment_id})
292
        return JsonResponse(LikeDislikeService.apply_comment_like(comment_id, session_id))
293
    else:
294
        return JsonResponse({"success": False, "msg": UNSUPPORTED_MESSAGE, "comment_id": comment_id})
295

296

297
def toggle_dislike_comment(request):
298
    comment_id = 0
299
300
301
302
    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:
303
            return JsonResponse({"success": False, "msg": MISSING_PARAMETER_MESSAGE, "comment_id": comment_id})
304
        return JsonResponse(LikeDislikeService.apply_comment_dislike(comment_id, session_id))
305
    else:
306
        return JsonResponse({"success": False, "msg": UNSUPPORTED_MESSAGE, "comment_id": comment_id})
307

308
def add_rating_materi(request):
309
    if request.method == "POST" and request.user.is_authenticated:
310

311
312
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
313

314
        is_valid_params, materi_id, \
315
316
317
            rating_score, response, \
            status_code = MateriFieldValidationHelperService.\
            validate_materi_rating_params(materi_id, rating_score)
318

319
320
        if not is_valid_params:
            return JsonResponse(response, status=status_code)
321

322
        is_valid_rating, materi, \
323
            response, status_code = MateriFieldValidationHelperService.\
324
            validate_materi_rating(materi_id, request.user)
325

326
327
        if not is_valid_rating:
            return JsonResponse(response, status=status_code)
328
329

        Rating(materi=materi, user=request.user, score=rating_score).save()
330
331
332
        return JsonResponse(
            {"success": True, "msg": "Rating successfully created", "rating_score": rating_score}, status=201
        )
333
334
335
    return JsonResponse({"success": False, "msg": "Forbidden"}, status=403)


336
337
338
339
340
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):
341
342
343
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
344
345
346
                return DownloadViewMateriHelperService.build_materi_response(fh, file_path,
                                                                             materi, mimetype, request,
                                                                             HttpResponse(fh.read(), content_type=mimetype[0]))
347
348
        except Exception:
            raise Http404(FILE_NOT_FOUND_MESSAGE)
349
    else:
350
        raise Http404(FILE_NOT_FOUND_MESSAGE)
351

igor lestin sianipar's avatar
igor lestin sianipar committed
352

353
354
355
356
357
358
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)
359
360
361
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
362
363
                DownloadViewMateriHelperService.build_view_materi_response(
                    file_path, materi, response)
364
                return response
365
366
        except Exception:
            raise Http404(FILE_NOT_FOUND_MESSAGE)
367
    else:
368
        raise Http404(FILE_NOT_FOUND_MESSAGE)
igor lestin sianipar's avatar
igor lestin sianipar committed
369

igor lestin sianipar's avatar
igor lestin sianipar committed
370

Selvy Fitriani's avatar
Selvy Fitriani committed
371
372
def delete_materi(request, pk):
    materi = get_object_or_404(Materi, pk=pk)
373
374
375
    if request.user.is_superuser or request.user.is_admin:
        materi.soft_delete()
        return HttpResponseRedirect("/administration/")
Selvy Fitriani's avatar
Selvy Fitriani committed
376
377
378
    materi.delete()
    return HttpResponseRedirect("/dashboard/")

379

igor lestin sianipar's avatar
igor lestin sianipar committed
380
class UploadMateriView(TemplateView):
381
    template_name = UNGGAH_HTML
igor lestin sianipar's avatar
igor lestin sianipar committed
382
    context = {}
383
    redirect_path = "/unggah/"
igor lestin sianipar's avatar
igor lestin sianipar committed
384
385
386
387
388

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

Saul Andre's avatar
Saul Andre committed
389
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
390
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
391
            raise PermissionDenied(request)
392
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
393
394
395
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
396
            konten = form.cleaned_data["content"]
397
398
            yt_url_id = form.cleaned_data['yt_video_id']
            if not UploadMateriService.validate_file_extension(konten, request, yt_url_id):
399
                return HttpResponseRedirect(UNGGAH_URL)
400
            UploadMateriService.upload_materi(form, materi)
401
402
            messages.success(
                request, "Materi berhasil diunggah, periksa riwayat unggah anda")
403
            return HttpResponseRedirect(UNGGAH_URL)
Saul Andre's avatar
Saul Andre committed
404
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
405
            context = self.get_context_data(**kwargs)
406
            context["form"] = form
407
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
408
409
410
            return self.render_to_response(context)

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

igor lestin sianipar's avatar
igor lestin sianipar committed
414
        context = self.get_context_data(**kwargs)
415
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
416
        return self.render_to_response(context)
417

418

419
class UploadMateriHTML(TemplateView):
420
    template_name = UNGGAH_HTML
421
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
422

423

424
425
426
427
428
class UploadMateriExcelView(TemplateView):
    template_name = "unggah_excel.html"
    context = {}

    def get_template_names(self):
429
        if self.request.path == UNGGAH_EXCEL_URL:
430
431
432
433
434
            template_name = "unggah_excel.html"
        return template_name

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

435
        if "template" in self.request.GET:
436

437
            data_frame = pd.DataFrame(
438
439
                {"Title": [], "Author": [], "Publisher": [],
                    "Categories": [], "Description": [], }
440
            )
441

442
            # pylint: disable=abstract-class-instantiated
443
            with BytesIO() as b:
444
445
                writer = pd.ExcelWriter(
                    b, engine="xlsxwriter")
446
447
448
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
449
450
                    b.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
451
452
453
454
455
456
457
458
459
460

                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):
461
462
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
463

464
        row, lines = excel.shape
465
        categories = Category.objects.all()
466

467
        field_length = {
468
469
470
            "title": 50,
            "author": 30,
            "publisher": 30,
471
472
473
474
475
476
        }

        message = None

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

478
            # Validate Categories
479
480
            message = UploadMateriService.validate_excel_categories(
                categories, excel, i, message)
481

482
483
            message = UploadMateriService.validate_excel_field_length(
                excel, field_length, i, message)
484
485
486

            if message != None:
                break
487

488
489
        if message != None:
            messages.error(request, message)
490
            return HttpResponseRedirect(UNGGAH_EXCEL_URL)
491
492
493

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

497
        messages.success(request, "Materi berhasil diunggah")
498

499
        return HttpResponseRedirect(UNGGAH_EXCEL_URL)
500
501


502
class DashboardKontributorView(TemplateView):
503
    template_name = "dashboard.html"
504
505
506
507
508
509
510

    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):
511
512
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
513
514
515
516
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
517
518
519
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
520
        return self.render_to_response(context)
521

522

523
class ProfilView(TemplateView):
524
525
526
    template_name = "profil.html"

    def dispatch(self, request, *args, **kwargs):
527
        if not request.user.is_authenticated:
528
            raise PermissionDenied(request)
529
        return super(ProfilView, self).dispatch(request, *args, **kwargs)
530
531
532

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

537

538
539
540
541
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
542
        if not request.user.is_authenticated:
543
544
545
546
            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
547
        current_user = self.request.user
548
549
550
551
552
553
554
555
556
557
        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
558

559
560
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
561
562
        if form.is_valid():
            current_user.default_profile_picture = True
563
564
565

            # Removing exifdata from profile picture on upload
            if request.FILES:
566
567
                EditProfileService.update_profile_picture(
                    current_user, request)
568
            else:
569
                form.save()
570
            return HttpResponseRedirect("/profil/")
571
572
        else:
            context = self.get_context_data(**kwargs)
573
574
            context["form"] = form
            return self.render_to_response(context)
575

576

577
578
579
580
581
class ReqMateriView(TemplateView):
    template_name = "req_materi.html"

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
582
            return HttpResponseRedirect(LOGIN_URL)
583
584
585
        return super(ReqMateriView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
586
        context = super(ReqMateriView, self).get_context_data(**kwargs)
587
588
589
590
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
591
        context['requested_material'] = ReqMaterial.objects.all()
592
593
594
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
595
        title = request.POST.get("title", None)
596
        if title is None:
597
            return JsonResponse({"success": False, "msg": MISSING_PARAMETER_MESSAGE})
598
599
600
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

601

602
603
604
605
606
607
608
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)
609

610
    def get_context_data(self, **kwargs):
611
612
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
613
614
615
616
617
618
619
620
621
622
        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)

623

624
625
626
class SuksesLoginAdminView(TemplateView):
    template_name = "sukses_admin.html"

627
628
629
630
    def getAdminNotification(self):
        notifications = AdminNotification.objects.all()
        return notifications

631
632
633
634
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_admin:
            raise PermissionDenied(request)
        return super(SuksesLoginAdminView, self).dispatch(request, *args, **kwargs)
635

636
637
638
639
640
641
642
643
644
645
    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

646
647
        notifications = self.getAdminNotification()
        context["notifications"] = notifications
648

649
        return self.render_to_response(context)
igor lestin sianipar's avatar
igor lestin sianipar committed
650

651
652
653
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
654
655

    def dispatch(self, request, *args, **kwargs):
656
        if not request.user.is_authenticated:
657
            raise PermissionDenied(request)
658
        return super(PostsView, self).dispatch(request, *args, **kwargs)
659
660

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

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

668
669
        comments = Comment.objects.filter(
            materi__id__in=posts_data.keys()).order_by("-timestamp")
670
671
672
673
674
675
676

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

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

677
        return self.render_to_response(context=context)
678

679

680
681
682
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

683
    def dispatch(self, request, *args, **kwargs):
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
        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)

699
    def post(self, request, *args, **kwargs):
700
701
702
703
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
704
705
706
707
708

        if request.user.is_authenticated and request.user.is_contributor:
            opened_notif = NotifikasiKontributor.objects.filter(user=request.user, materi=current_materi)
            opened_notif.delete()
        
709
710
        form = UploadMateriForm(
            request.POST, request.FILES, instance=current_materi)
711
        if form.is_valid():
712
            RevisiMateriService.revisi_materi(form, request)
713
714
715
716
717
718
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

719

Samuel Dimas's avatar
Samuel Dimas committed
720
721
722
723
724
725
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

726
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
727
728
729
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

730
    except Exception:
Samuel Dimas's avatar
Samuel Dimas committed
731

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


736
737
738
739
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
740
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
741
742
743
744
745
746
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
747
748
            DownloadHistoryService.init_data_authenticated_user(
                context, current_user)
749
        else:
750
            DownloadHistoryService.init_data_guest_user(context, request)
751
        return self.render_to_response(context)
752

753

754
755
756
757
758
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):
759
        GoogleDriveUploadService.upload_to_gdrive(file_path, materi.title)
760
    else:
761
        raise Http404(FILE_NOT_FOUND_MESSAGE)
762

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

765

766
767
768
769
770
771
772
773
774
775
776
777
778
779
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)
780
        likes_data = {mat.id: {"data": mat, "comments": []} for mat in materi}
781
782
783
784
785
786
787
788
789
790
791
792
793

        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)

794

Yaumi's avatar
Yaumi committed
795
class PasswordChangeViews(PasswordChangeView):
796

Yaumi's avatar
Yaumi committed
797
798
    from_class = PasswordChangeForm
    success_url = reverse_lazy('password_success')
Yaumi's avatar
Yaumi committed
799

800

Yaumi's avatar
Yaumi committed
801
def password_success(request):
802
    return render(request, 'password_success.html', {})
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818


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:]
819
820
            rating_list = Rating.objects.filter(
                user=request.user).order_by(query_order + order_by_key)
821
822
        except FieldError:
            order_by_key = 'timestamp'
823
824
            rating_list = Rating.objects.filter(
                user=request.user).order_by(query_order + order_by_key)
825
826
827
828

        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
829

830

insan ramadhan's avatar
insan ramadhan committed
831
832
833
834
835
class SubmitVisitorView(TemplateView):
    template_name = "submit_visitor.html"

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
836
            return HttpResponseRedirect(LOGIN_URL)
insan ramadhan's avatar
insan ramadhan committed
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
        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:
852
            return JsonResponse({"success": False, "msg": MISSING_PARAMETER_MESSAGE})
insan ramadhan's avatar
insan ramadhan committed
853
854
        SubmitVisitor(msg=title, user_id=user_id, email=email).save()
        return JsonResponse({"success": True, "msg": "Buku tamu berhasil ditambahkan"})
855

856
857
858
859
860
861
862
863
864
865
866
867
868
869
870

class GuestBookView(TemplateView):
    def get(self, request, *args, **kwargs):
        form = GuestBookForm()
        return render(request, 'guest_book.html', {'form': form})

    def post(self, request, *args, **kwargs):
        name = request.POST.get('name')
        job = request.POST.get('job')
        gender = request.POST.get('gender')
        guestBook = GuestBook(name=name, job=job, gender=gender)
        guestBook.save()
        return redirect("daftar_katalog")


Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
871
872
873
874
875
876
877