Fakultas Ilmu Komputer UI

views.py 34.7 KB
Newer Older
1
2
import mimetypes
import os
3
import datetime
4
5

from django.conf import settings
6
from django.contrib import messages
7
from django.contrib.auth.models import AnonymousUser
8
from django.core.exceptions import PermissionDenied, ValidationError
Mika dabelza abi's avatar
Mika dabelza abi committed
9
from django.db.models import Q, Count
10
11
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
12
from django.urls import reverse
13
from django.shortcuts import get_object_or_404, redirect
14
from django.template import loader
15
16
from django.views import defaults
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
17
from django.views.generic import TemplateView
18
from administration.models import VerificationReport
19
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm
20
21
22
from app.models import (
    Category,
    Comment,
23
    DislikeComment,
24
25
    Materi,
    Like,
26
    LikeComment,
27
28
29
30
31
32
    ViewStatistics,
    DownloadStatistics,
    ReqMaterial,
    Rating,
    RatingContributor,
)
33
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
34
from authentication.models import User
35
import django
36
37
import pandas as pd
from io import BytesIO
38
from django.contrib import messages
39
40
41
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from pydrive.auth import AuthenticationRejected
42
import random
43

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

47

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

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

62
        getSearch = request.GET.get("search")
63
        if getSearch:
Mika dabelza abi's avatar
Mika dabelza abi committed
64
            url = url + "&search={0}".format(getSearch)
65
66
67
68
69
70
71
72
73
74
            lstMateri = (
                lstMateri.search(getSearch)
                .filter(
                    Q(author__icontains=getSearch)
                    | Q(uploader__name__icontains=getSearch)
                    | Q(descriptions__icontains=getSearch)
                    | Q(publisher__icontains=getSearch)
                )
                .distinct()
            )
Saul Andre's avatar
Saul Andre committed
75

76
77
        getKategori = request.GET.get("kategori")
        if getKategori:
Mika dabelza abi's avatar
Mika dabelza abi committed
78
79
            url = url + "&kategori={0}".format(getKategori)
            kategori = Category.objects.get(pk=getKategori)
Mika dabelza abi's avatar
Mika dabelza abi committed
80
            lstMateri = lstMateri.filter(categories=kategori.pk)
81

82
        getSort = request.GET.get("sort")
83
        if getSort:
Mika dabelza abi's avatar
Mika dabelza abi committed
84
            url = url + "&sort={0}".format(getSort)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
            if(getSort == "judul"):
                lstMateri = lstMateri.order_by('title')
            elif(getSort == "penulis"):
                lstMateri = lstMateri.order_by('author')
            elif(getSort == "pengunggah"):
                lstMateri = lstMateri.order_by('uploader')
            elif(getSort == "terbaru"):
                lstMateri = lstMateri.order_by('-date_created')
            elif(getSort == "terlama"):
                lstMateri = lstMateri.order_by('date_created')
            elif(getSort == "terpopuler"):
                lstMateri = lstMateri.annotate(count=Count('like__id')).order_by('-count')
            elif(getSort == "jumlah_unduh"):
                lstMateri = lstMateri.annotate(count=Count('unduh__id')).order_by('-count')
99

100
101
102
103
        should_random = bool(request.GET.get("random"))
        if should_random:
            lstMateri = random.sample(list(lstMateri), len(lstMateri))

Mika dabelza abi's avatar
Mika dabelza abi committed
104
        context["materi_list"] = lstMateri
Mika dabelza abi's avatar
Mika dabelza abi committed
105
        paginator = Paginator(context["materi_list"], 15)
106
        page_number = request.GET.get("page")
Mika dabelza abi's avatar
Mika dabelza abi committed
107
108
109
110
        page_obj = paginator.get_page(page_number)
        context["materi_list"] = page_obj

        context["url"] = url
111
112
        return self.render_to_response(context=context)

113

114
115
class KatalogPerKontributorView(TemplateView):
    template_name = "app/katalog_kontri.html"
116

117
118
119
120
121
122
123
124
    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)
125
126
127
128
129

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

130
        paginator = Paginator(materi_list, 15)
131
        page_number = request.GET.get("page")
132
133
        materi_list_by_page = paginator.get_page(page_number)
        context["materi_list"] = materi_list_by_page
134
        contributor = get_object_or_404(User, email=kwargs["email"])
135
        context["form_rating"] = RatingContributorForm(initial={"user": contributor})
136
        return self.render_to_response(context=context)
137

138
139
140
141
    def post(self, request, *args, **kwargs):
        data = RatingContributorForm(request.POST)
        if data.is_valid():
            data.save()
142
143
        return redirect("katalog-per-kontributor", email=kwargs["email"])

144

145
146
147
148
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
149
150
151
152
153
154
        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"])
        context["session_id"] = self.request.session.session_key
        context["materi_data"] = materi
155
        context["report"] = VerificationReport.objects.filter(materi=materi)
156
157
158
159
160
161
162
        context["has_liked"] = Like.objects.filter(materi=materi, session_id=self.request.session.session_key).exists()
        publishedDate = ""
        if materi.published_date == None:
            publishedDate = "n.d"
        else:
            publishedDate = materi.published_date.strftime("%Y-%m-%d %H:%M")
        citationAPA = materi.author + " . (" + publishedDate + ") . " + materi.title + " . " + materi.publisher
163
        context["citationAPA"] = citationAPA
164
        context["citationIEEE"] = get_citation_ieee(self.request, materi)
165
        context["materi_rating_score"] = 0
166
167
168
169

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

174
        return context
175
176
177

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
178
        query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
179
180
181
182
183
        has_liked = {}
        has_disliked = {}
        for comment in query_set_for_comment:
            has_liked[comment.id] = LikeComment.objects.filter(comment=comment, session_id=self.request.session.session_key).exists()
            has_disliked[comment.id] = DislikeComment.objects.filter(comment=comment, session_id=self.request.session.session_key).exists()
184
        context["comment_data"] = query_set_for_comment
185
186
        context["has_liked"] = has_liked
        context["has_disliked"] = has_disliked
187
188
        return self.render_to_response(context=context)

189
190
    def get_user_name(self, request):
        user_name = ""
191
192
193
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
194
195
196
197
198
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

199
    def post(self, request, *args, **kwargs):
200
        commentText = request.POST.get("comment", None)
201
        if commentText == None or commentText == "":
202
203
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
204
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
205
            query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
206
            context["comment_data"] = query_set_for_comment
207
            return self.render_to_response(context=context)
208

209
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
210
        user_obj = request.user if request.user.is_authenticated else None
211
212
213
214
215
        if user_obj:
            comment = Comment.objects.create(
                comment=commentText, username=self.get_user_name(request), materi=materi, user=user_obj
            )
            comment.save()
216
217
        return HttpResponseRedirect(request.path)

218

219
def toggle_like(request):
220
221
222
    if request.method == "POST":
        materi_id = request.POST.get("materi_id", None)
        session_id = request.POST.get("session_id", None)
223
224
225
        if materi_id is None or session_id is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        materi = get_object_or_404(Materi, pk=materi_id)
226
        has_liked = Like.objects.filter(materi=materi, session_id=session_id).exists()
227
        if has_liked:
228
            like = get_object_or_404(Like, materi=materi, session_id=session_id)
229
230
231
232
233
234
235
236
237
            like.delete()
            return JsonResponse({"success": True, "liked": True})
        else:
            Like(materi=materi, session_id=session_id).save()
            return JsonResponse({"success": True, "liked": False})
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method"})


238
def delete_comment(request, pk_materi, pk_comment):
239
240
    if not request.user.is_authenticated or not request.user.is_admin:
        raise PermissionDenied(request)
241
    comment = get_object_or_404(Comment, pk=pk_comment)
242
    url = "/materi/" + str(pk_materi) + "/"
243
244
245
    comment.delete()
    return HttpResponseRedirect(url)

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def toggle_like_comment(request):
    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})
        comment = get_object_or_404(Comment, pk=comment_id)
        has_liked = LikeComment.objects.filter(comment=comment, session_id=session_id).exists()
        if has_liked:
            like = get_object_or_404(LikeComment, comment=comment, session_id=session_id)
            like.delete()
            return JsonResponse({"success": True, "liked": True, "comment_id": comment_id})
        else:
            LikeComment(comment=comment, session_id=session_id).save()
            return JsonResponse({"success": True, "liked": False, "comment_id": comment_id})
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})

def toggle_dislike_comment(request):
    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})
        comment = get_object_or_404(Comment, pk=comment_id)
        has_disliked = DislikeComment.objects.filter(comment=comment, session_id=session_id).exists()
        if has_disliked:
            dislike = get_object_or_404(DislikeComment, comment=comment, session_id=session_id)
            dislike.delete()
            return JsonResponse({"success": True, "disliked": True, "comment_id": comment_id})
        else:
            DislikeComment(comment=comment, session_id=session_id).save()
            return JsonResponse({"success": True, "disliked": False, "comment_id": comment_id})
    else:
        return JsonResponse({"success": False, "msg": "Unsuported method", "comment_id": comment_id})
281

282
283
284
285
286
287
def get_citation_ieee(request, materi):
    current_date = datetime.datetime.now()
    current_day = str(current_date.day)
    current_month = current_date.strftime("%b")
    current_year = str(current_date.year)
    published_date = ""
288
    if materi.published_date == None:
289
        published_date = "n.d"
290
291
292
    else:
        published_date = materi.published_date.strftime("%Y")

293
294
295
296
297
298
    author_list = materi.author.split(",")
    author_list_abbrv = ""
    for author_name in author_list:
        author_name_split = author_name.split(" ")
        author_name_abbrv = ""
        for j, name in enumerate(author_name_split):
299
            if j < (len(author_name_split) - 1):
300
301
302
303
304
305
                abbrv_name = name[0].upper()
                author_name_abbrv = author_name_abbrv + abbrv_name + ". "
            else:
                author_name_abbrv = author_name_abbrv + name
        author_list_abbrv = author_list_abbrv + author_name_abbrv + ", "

306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
    citation_result = (
        author_list_abbrv
        + materi.title
        + ". "
        + materi.publisher
        + ", "
        + published_date
        + ". "
        + "Accessed on: "
        + current_month
        + ". "
        + current_day
        + ", "
        + current_year
        + ". [Online]. "
        + "Available: "
        + request.build_absolute_uri()
    )
324
    return citation_result
325

326

327
def add_rating_materi(request):
328
    if request.method == "POST" and request.user.is_authenticated:
329

330
331
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

        if materi_id is None or rating_score is None:
            return JsonResponse({"success": False, "msg": "Missing param"}, status=422)
        try:
            rating_score = int(rating_score)
        except ValueError:
            return JsonResponse({"success": False, "msg": "rating_score must be an integer"}, status=422)

        try:
            materi_id = int(materi_id)
        except ValueError:
            return JsonResponse({"success": False, "msg": "materi_id must be an integer"}, status=422)

        if rating_score not in range(1, 6):
            return JsonResponse({"success": False, "msg": "Rating must be an integer from 1 to 5"}, status=422)

        materi = Materi.objects.filter(pk=materi_id).first()

        if materi is None:
            return JsonResponse({"success": False, "msg": "Materi does not exist"}, status=422)

        if Rating.objects.filter(materi=materi, user=request.user).first() is not None:
            return JsonResponse({"success": False, "msg": "Rating already exist"}, status=409)

        Rating(materi=materi, user=request.user, score=rating_score).save()
357
358
359
        return JsonResponse(
            {"success": True, "msg": "Rating successfully created", "rating_score": rating_score}, status=201
        )
360
361
362
    return JsonResponse({"success": False, "msg": "Forbidden"}, status=403)


363
364
365
366
367
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):
368
369
370
371
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
372
                response["Content-Disposition"] = "attachment; filename=" + os.path.basename(file_path)
373
374
375
376
                if request.user.is_authenticated:
                    DownloadStatistics(materi=materi, downloader=request.user).save()
                else:
                    downloaded_materi = DownloadStatistics.objects.create(materi=materi)
377
378
379
                    if "downloaded_materi" not in request.session:
                        request.session["downloaded_materi"] = []
                    request.session["downloaded_materi"].append(downloaded_materi.pk)
380
                    request.session.modified = True
381
382
383
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
384
385
386
    else:
        raise Http404("File tidak dapat ditemukan.")

igor lestin sianipar's avatar
igor lestin sianipar committed
387

388
389
390
391
392
393
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)
394
395
396
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
397
                response["Content-Disposition"] = "inline; filename=" + os.path.basename(file_path)
398
399
400
401
                ViewStatistics(materi=materi).save()
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
402
403
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
404

igor lestin sianipar's avatar
igor lestin sianipar committed
405

Selvy Fitriani's avatar
Selvy Fitriani committed
406
407
408
409
410
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
411
class UploadMateriView(TemplateView):
412
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
413
414
415
416
417
418
    context = {}

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

Saul Andre's avatar
Saul Andre committed
419
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
420
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
421
            raise PermissionDenied(request)
422
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
423
424
425
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
426
            konten = form.cleaned_data["content"]
427
428
429
430
431
            try:
                self.validate_file_extension(konten)
            except ValidationError:
                messages.error(request, "Materi gagal diunggah, format file tidak sesuai")
                return HttpResponseRedirect("/unggah/")
igor lestin sianipar's avatar
igor lestin sianipar committed
432
            materi.save()
433
            kateg = form.cleaned_data["categories"]
434
435
            for i in kateg:
                materi.categories.add(i)
436
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
437
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
438
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
439
            context = self.get_context_data(**kwargs)
440
            context["form"] = form
441
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
442
443
444
            return self.render_to_response(context)

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

igor lestin sianipar's avatar
igor lestin sianipar committed
448
        context = self.get_context_data(**kwargs)
449
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
450
        return self.render_to_response(context)
451

452
453
    def validate_file_extension(self, value):
        ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
454
        valid_extensions = [".pdf", ".doc", ".docx", ".jpg", ".png", ".xlsx", ".xls", ".mp4", ".mp3"]
455
        if not ext.lower() in valid_extensions:
456
            raise ValidationError("Unsupported file extension.")
457

Samuel Dimas's avatar
Samuel Dimas committed
458

459
460
461
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
462

463
464
465
466
467
468
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


469
470
471
472
473
474
475
476
477
478
479
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):

480
        if "template" in self.request.GET:
481

482
483
484
            data_frame = pd.DataFrame(
                {"Title": [], "Author": [], "Publisher": [], "Categories": [], "Description": [],}
            )
485
486

            with BytesIO() as b:
487
                writer = pd.ExcelWriter(b, engine="xlsxwriter")  # pylint: disable=abstract-class-instantiated
488
489
490
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
491
492
                    b.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
493
494
495
496
497
498
499
500
501
502

                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):
503
504
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
505

506
        row, lines = excel.shape
507
        categories = Category.objects.all()
508

509
        field_length = {
510
511
512
            "title": 50,
            "author": 30,
            "publisher": 30,
513
514
515
516
517
518
        }

        message = None

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

520
            # Validate Categories
521
            for c in excel["Categories"][i].split(","):
522
523
524
525
526
                sel_cat = categories.filter(name=c)
                if sel_cat.count() == 0:
                    message = f"Kategori %s tidak ditemukan" % c
                    break

527
528
            if len(excel["Title"][i]) > field_length["title"]:
                message = f"Title maksimal %d karakter" % field_length["title"]
529

530
531
            if len(excel["Author"][i]) > field_length["author"]:
                message = f"Author maksimal %d karakter" % field_length["author"]
532

533
534
            if len(excel["Publisher"][i]) > field_length["publisher"]:
                message = f"Publisher maksimal %d karakter" % field_length["publisher"]
535
536
537

            if message != None:
                break
538

539
540
        if message != None:
            messages.error(request, message)
541
            return HttpResponseRedirect("/unggah_excel/")
542
543
544
545
546

        # Second pass, save data
        with django.db.transaction.atomic():
            for i in range(row):
                materi = Materi(
547
548
549
550
551
552
                    title=excel["Title"][i],
                    author=excel["Author"][i],
                    publisher=excel["Publisher"][i],
                    descriptions=excel["Description"][i],
                    uploader=request.user,
                )
553
                materi.save()
554
555

                for c in excel["Categories"][i].split(","):
556
557
                    materi.categories.add(categories.get(name=c))

558
        messages.success(request, "Materi berhasil diunggah")
559

560
        return HttpResponseRedirect("/unggah_excel/")
561
562


563
class DashboardKontributorView(TemplateView):
564
    template_name = "dashboard.html"
565
566
567
568
569
570
571

    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):
572
        context = super(DashboardKontributorView, self).get_context_data(**kwargs)
573
574
575
576
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
577
578
579
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
580
        return self.render_to_response(context)
581

582

583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
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)
600

601

602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
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)

620

621
622
623
624
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
625
        if not request.user.is_authenticated or not request.user.is_contributor:
626
627
628
629
630
631
632
633
634
635
636
637
638
            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
639
        context["form"] = SuntingProfilForm(instance=current_user)
640
641
642
643
644
645
        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
646
        current_user = self.request.user
647

648
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
649
        if form.is_valid():
650
            current_user.default_profile_picture = True
651
652
653

            # Removing exifdata from profile picture on upload
            if request.FILES:
654
                f_name = request.FILES["profile_picture"].name
655
656
                f_name = get_random_filename(f_name)
                f_path = settings.MEDIA_ROOT + "/" + f_name
657
                request.FILES["profile_picture"].name = f_name
658

659
                form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
660
661
662
                form.save()

                remove_image_exifdata(f_path)
663
            else:
664
                form.save()
665
666
667
668
669
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
670

igor lestin sianipar's avatar
igor lestin sianipar committed
671

672
673
674
675
676
677
678
679
680
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):
681
        context = super(SuntingProfilAdminView, self).get_context_data(**kwargs)
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
        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
698

699
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
700
701
        if form.is_valid():
            current_user.default_profile_picture = True
702
703
704

            # Removing exifdata from profile picture on upload
            if request.FILES:
705
                f_name = request.FILES["profile_picture"].name
706
707
                f_name = get_random_filename(f_name)
                f_path = settings.MEDIA_ROOT + "/" + f_name
708
                request.FILES["profile_picture"].name = f_name
709

710
                form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
711
712
713
                form.save()

                remove_image_exifdata(f_path)
714
            else:
715
                form.save()
716
717
718
            return HttpResponseRedirect("/profil-admin/")
        else:
            context = self.get_context_data(**kwargs)
719
720
            context["form"] = form
            return self.render_to_response(context)
721

722

723
724
725
726
727
728
729
730
731
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):
732
        context = super(ReqMateriView, self).get_context_data(**kwargs)
733
734
735
736
737
738
739
        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):
740
        title = request.POST.get("title", None)
741
742
743
744
745
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

746

747
748
749
750
751
752
753
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)
754

755
    def get_context_data(self, **kwargs):
756
        context = super(SuksesLoginKontributorView, self).get_context_data(**kwargs)
757
758
759
760
761
762
763
764
765
766
        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)

767

768
769
770
771
772
773
774
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)
775

776
777
778
779
780
781
782
783
784
785
786
787
    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
788

789
790
791
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
792
793

    def dispatch(self, request, *args, **kwargs):
794
        if not request.user.is_authenticated:
795
            raise PermissionDenied(request)
796
        return super(PostsView, self).dispatch(request, *args, **kwargs)
797
798

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

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

805
        comments = Comment.objects.filter(materi__id__in=posts_data.keys()).order_by("-timestamp")
806
807
808
809
810
811
812

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

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

813
        return self.render_to_response(context=context)
814

815

816
817
818
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

819
    def dispatch(self, request, *args, **kwargs):
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
        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)

835
    def post(self, request, *args, **kwargs):
836
837
838
839
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
840
        form = UploadMateriForm(request.POST, request.FILES, instance=current_materi)
841
842
843
844
845
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.status = "REVISION"
            materi.save()
846
            kateg = form.cleaned_data["categories"]
847
848
849
850
851
852
853
854
855
            for i in kateg:
                materi.categories.add(i)
            materi.save()
            return HttpResponseRedirect("/dashboard/")
        else:
            context = self.get_context_data(**kwargs)
            context["form_revisi"] = form
            return self.render_to_response(context)

856

Samuel Dimas's avatar
Samuel Dimas committed
857
858
859
860
861
862
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

863
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
864
865
866
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

867
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
868

869
        template = loader.get_template("error-404.html")
Samuel Dimas's avatar
Samuel Dimas committed
870
        return HttpResponse(template.render(context, request))
871
872


873
874
875
876
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
877
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
878
879
880
881
882
883
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
884
            riwayat_list = current_user.riwayat_unduh.all().order_by("-timestamp")
885
886
887
            context["riwayat_list"] = riwayat_list
            context["user_name"] = current_user.name
        else:
888
889
890
            has_downloaded_materi = "downloaded_materi" in request.session
            downloaded_materi = request.session["downloaded_materi"] if has_downloaded_materi else []
            riwayat_list = DownloadStatistics.objects.filter(pk__in=downloaded_materi).order_by("-timestamp")
891
            context["riwayat_list"] = riwayat_list
892
            context["user_name"] = "Guest"
893
        return self.render_to_response(context)
894

895

896
897
898
899
900
901
902
def upload_to_gdrive(file_path, title):
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()

    drive = GoogleDrive(gauth)
    file1 = drive.CreateFile()
    file1.SetContentFile(file_path)
903
904
    file1["title"] = title
    print("title: %s, mimeType: %s" % (file1["title"], file1["mimeType"]))
905
906
    file1.Upload()

907

908
909
910
911
912
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):
913
        upload_to_gdrive(file_path, materi.title)
914
915
916
    else:
        raise Http404("File tidak dapat ditemukan.")

917
    return HttpResponseRedirect(reverse('detail-materi', kwargs={'pk': pk}))