Fakultas Ilmu Komputer UI

views.py 31.5 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
from django.http import Http404, HttpResponse, HttpResponseRedirect, JsonResponse
11
from django.urls import reverse
12
from django.shortcuts import get_object_or_404, redirect
13
from django.template import loader
14
15
from django.views import defaults
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
16
from django.views.generic import TemplateView
17
from administration.models import VerificationReport
18
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm
19
20
21
22
23
24
25
26
27
28
29
from app.models import (
    Category,
    Comment,
    Materi,
    Like,
    ViewStatistics,
    DownloadStatistics,
    ReqMaterial,
    Rating,
    RatingContributor,
)
30
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
31
from authentication.models import User
32
import django
33
34
import pandas as pd
from io import BytesIO
35
36
37
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from pydrive.auth import AuthenticationRejected
38

39
40

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

43

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

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

58
        getSearch = request.GET.get("search")
59
        if getSearch:
Mika dabelza abi's avatar
Mika dabelza abi committed
60
            url = url + "&search={0}".format(getSearch)
61
62
63
64
65
66
67
68
69
70
            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
71

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

78
        getSort = request.GET.get("sort")
79
        if getSort:
Mika dabelza abi's avatar
Mika dabelza abi committed
80
            url = url + "&sort={0}".format(getSort)
81
82
83
84
85
86
87
88
89
90
91
92
            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")
93

Mika dabelza abi's avatar
Mika dabelza abi committed
94
        context["materi_list"] = lstMateri
Mika dabelza abi's avatar
Mika dabelza abi committed
95
        paginator = Paginator(context["materi_list"], 15)
96
        page_number = request.GET.get("page")
Mika dabelza abi's avatar
Mika dabelza abi committed
97
98
99
100
        page_obj = paginator.get_page(page_number)
        context["materi_list"] = page_obj

        context["url"] = url
101
102
        return self.render_to_response(context=context)

103

104
105
class KatalogPerKontributorView(TemplateView):
    template_name = "app/katalog_kontri.html"
106

107
108
109
110
111
112
113
114
    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)
115
116
117
118
119

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

120
        paginator = Paginator(materi_list, 15)
121
        page_number = request.GET.get("page")
122
123
        materi_list_by_page = paginator.get_page(page_number)
        context["materi_list"] = materi_list_by_page
124
        contributor = get_object_or_404(User, email=kwargs["email"])
125
        context["form_rating"] = RatingContributorForm(initial={"user": contributor})
126
        return self.render_to_response(context=context)
127

128
129
130
131
    def post(self, request, *args, **kwargs):
        data = RatingContributorForm(request.POST)
        if data.is_valid():
            data.save()
132
133
        return redirect("katalog-per-kontributor", email=kwargs["email"])

134

135
136
137
138
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
139
140
141
142
143
144
        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
145
        context["report"] = VerificationReport.objects.filter(materi=materi)
146
147
148
149
150
151
152
        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
153
        context["citationAPA"] = citationAPA
154
        context["citationIEEE"] = get_citation_ieee(self.request, materi)
155
        context["materi_rating_score"] = 0
156
157
158
159

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

162
        return context
163
164
165

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
166
        query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
167
        context["comment_data"] = query_set_for_comment
168
169
        return self.render_to_response(context=context)

170
171
    def get_user_name(self, request):
        user_name = ""
172
173
174
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
175
176
177
178
179
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

180
    def post(self, request, *args, **kwargs):
181
        commentText = request.POST.get("comment", None)
182
        if commentText == None or commentText == "":
183
184
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
185
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
186
            query_set_for_comment = Comment.objects.filter(materi=context["materi_data"])
187
            context["comment_data"] = query_set_for_comment
188
            return self.render_to_response(context=context)
189

190
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
191
        user_obj = request.user if request.user.is_authenticated else None
192
193
194
        comment = Comment.objects.create(
            comment=commentText, username=self.get_user_name(request), materi=materi, user=user_obj
        )
195
196
197
        comment.save()
        return HttpResponseRedirect(request.path)

198

199
def toggle_like(request):
200
201
202
    if request.method == "POST":
        materi_id = request.POST.get("materi_id", None)
        session_id = request.POST.get("session_id", None)
203
204
205
        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)
206
        has_liked = Like.objects.filter(materi=materi, session_id=session_id).exists()
207
        if has_liked:
208
            like = get_object_or_404(Like, materi=materi, session_id=session_id)
209
210
211
212
213
214
215
216
217
            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"})


218
219
def delete_comment(request, pk_materi, pk_comment):
    comment = get_object_or_404(Comment, pk=pk_comment)
220
    url = "/materi/" + str(pk_materi) + "/"
221
222
223
    comment.delete()
    return HttpResponseRedirect(url)

224

225
226
227
228
229
230
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 = ""
231
    if materi.published_date == None:
232
        published_date = "n.d"
233
234
235
    else:
        published_date = materi.published_date.strftime("%Y")

236
237
238
239
240
241
    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):
242
            if j < (len(author_name_split) - 1):
243
244
245
246
247
248
                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 + ", "

249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    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()
    )
267
    return citation_result
268

269

270
def add_rating_materi(request):
271
    if request.method == "POST" and request.user.is_authenticated:
272

273
274
        materi_id = request.POST.get("materi_id", None)
        rating_score = request.POST.get("rating_score", None)
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299

        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()
300
301
302
        return JsonResponse(
            {"success": True, "msg": "Rating successfully created", "rating_score": rating_score}, status=201
        )
303
304
305
    return JsonResponse({"success": False, "msg": "Forbidden"}, status=403)


306
307
308
309
310
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):
311
312
313
314
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
315
                response["Content-Disposition"] = "attachment; filename=" + os.path.basename(file_path)
316
317
318
319
                if request.user.is_authenticated:
                    DownloadStatistics(materi=materi, downloader=request.user).save()
                else:
                    downloaded_materi = DownloadStatistics.objects.create(materi=materi)
320
321
322
                    if "downloaded_materi" not in request.session:
                        request.session["downloaded_materi"] = []
                    request.session["downloaded_materi"].append(downloaded_materi.pk)
323
                    request.session.modified = True
324
325
326
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
327
328
329
    else:
        raise Http404("File tidak dapat ditemukan.")

igor lestin sianipar's avatar
igor lestin sianipar committed
330

331
332
333
334
335
336
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)
337
338
339
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
340
                response["Content-Disposition"] = "inline; filename=" + os.path.basename(file_path)
341
342
343
344
                ViewStatistics(materi=materi).save()
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
345
346
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
347

igor lestin sianipar's avatar
igor lestin sianipar committed
348

igor lestin sianipar's avatar
igor lestin sianipar committed
349
class UploadMateriView(TemplateView):
350
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
351
352
353
354
355
356
    context = {}

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

Saul Andre's avatar
Saul Andre committed
357
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
358
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
359
            raise PermissionDenied(request)
360
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
361
362
363
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
364
            konten = form.cleaned_data["content"]
365
366
367
368
369
            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
370
            materi.save()
371
            kateg = form.cleaned_data["categories"]
372
373
            for i in kateg:
                materi.categories.add(i)
374
            messages.success(request, "Materi berhasil diunggah, periksa riwayat unggah anda")
375
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
376
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
377
            context = self.get_context_data(**kwargs)
378
            context["form"] = form
379
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
380
381
382
            return self.render_to_response(context)

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

igor lestin sianipar's avatar
igor lestin sianipar committed
386
        context = self.get_context_data(**kwargs)
387
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
388
        return self.render_to_response(context)
389

390
391
    def validate_file_extension(self, value):
        ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
392
        valid_extensions = [".pdf", ".doc", ".docx", ".jpg", ".png", ".xlsx", ".xls", ".mp4", ".mp3"]
393
        if not ext.lower() in valid_extensions:
394
            raise ValidationError("Unsupported file extension.")
395

Samuel Dimas's avatar
Samuel Dimas committed
396

397
398
399
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
400

401
402
403
404
405
406
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


407
408
409
410
411
412
413
414
415
416
417
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):

418
        if "template" in self.request.GET:
419

420
421
422
            data_frame = pd.DataFrame(
                {"Title": [], "Author": [], "Publisher": [], "Categories": [], "Description": [],}
            )
423
424

            with BytesIO() as b:
425
                writer = pd.ExcelWriter(b, engine="xlsxwriter")  # pylint: disable=abstract-class-instantiated
426
427
428
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
429
430
                    b.getvalue(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                )
431
432
433
434
435
436
437
438
439
440

                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):
441
442
        excel_file = request.FILES["excel"]
        excel = pd.read_excel(excel_file)
443

444
        row, lines = excel.shape
445
        categories = Category.objects.all()
446

447
        field_length = {
448
449
450
            "title": 50,
            "author": 30,
            "publisher": 30,
451
452
453
454
455
456
        }

        message = None

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

458
            # Validate Categories
459
            for c in excel["Categories"][i].split(","):
460
461
462
463
464
                sel_cat = categories.filter(name=c)
                if sel_cat.count() == 0:
                    message = f"Kategori %s tidak ditemukan" % c
                    break

465
466
            if len(excel["Title"][i]) > field_length["title"]:
                message = f"Title maksimal %d karakter" % field_length["title"]
467

468
469
            if len(excel["Author"][i]) > field_length["author"]:
                message = f"Author maksimal %d karakter" % field_length["author"]
470

471
472
            if len(excel["Publisher"][i]) > field_length["publisher"]:
                message = f"Publisher maksimal %d karakter" % field_length["publisher"]
473
474
475

            if message != None:
                break
476

477
478
        if message != None:
            messages.error(request, message)
479
            return HttpResponseRedirect("/unggah_excel/")
480
481
482
483
484

        # Second pass, save data
        with django.db.transaction.atomic():
            for i in range(row):
                materi = Materi(
485
486
487
488
489
490
                    title=excel["Title"][i],
                    author=excel["Author"][i],
                    publisher=excel["Publisher"][i],
                    descriptions=excel["Description"][i],
                    uploader=request.user,
                )
491
                materi.save()
492
493

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

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

498
        return HttpResponseRedirect("/unggah_excel/")
499
500


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

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

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

520

521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
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)
538

539

540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
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)

558

559
560
561
562
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
563
        if not request.user.is_authenticated or not request.user.is_contributor:
564
565
566
567
568
569
570
571
572
573
574
575
576
            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
577
        context["form"] = SuntingProfilForm(instance=current_user)
578
579
580
581
582
583
        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
584
        current_user = self.request.user
585

586
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
587
        if form.is_valid():
588
            current_user.default_profile_picture = True
589
590
591

            # Removing exifdata from profile picture on upload
            if request.FILES:
592
                f_name = request.FILES["profile_picture"].name
593
594
                f_name = get_random_filename(f_name)
                f_path = settings.MEDIA_ROOT + "/" + f_name
595
                request.FILES["profile_picture"].name = f_name
596

597
                form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
598
599
600
                form.save()

                remove_image_exifdata(f_path)
601
            else:
602
                form.save()
603
604
605
606
607
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
608

igor lestin sianipar's avatar
igor lestin sianipar committed
609

610
611
612
613
614
615
616
617
618
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):
619
        context = super(SuntingProfilAdminView, self).get_context_data(**kwargs)
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
        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
636

637
        form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
638
639
        if form.is_valid():
            current_user.default_profile_picture = True
640
641
642

            # Removing exifdata from profile picture on upload
            if request.FILES:
643
                f_name = request.FILES["profile_picture"].name
644
645
                f_name = get_random_filename(f_name)
                f_path = settings.MEDIA_ROOT + "/" + f_name
646
                request.FILES["profile_picture"].name = f_name
647

648
                form = SuntingProfilForm(request.POST, request.FILES, instance=current_user)
649
650
651
                form.save()

                remove_image_exifdata(f_path)
652
            else:
653
                form.save()
654
655
656
            return HttpResponseRedirect("/profil-admin/")
        else:
            context = self.get_context_data(**kwargs)
657
658
            context["form"] = form
            return self.render_to_response(context)
659

660

661
662
663
664
665
666
667
668
669
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):
670
        context = super(ReqMateriView, self).get_context_data(**kwargs)
671
672
673
674
675
676
677
        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):
678
        title = request.POST.get("title", None)
679
680
681
682
683
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

684

685
686
687
688
689
690
691
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)
692

693
    def get_context_data(self, **kwargs):
694
        context = super(SuksesLoginKontributorView, self).get_context_data(**kwargs)
695
696
697
698
699
700
701
702
703
704
        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)

705

706
707
708
709
710
711
712
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)
713

714
715
716
717
718
719
720
721
722
723
724
725
    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
726

727
728
729
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
730
731

    def dispatch(self, request, *args, **kwargs):
732
        if not request.user.is_authenticated:
733
            raise PermissionDenied(request)
734
        return super(PostsView, self).dispatch(request, *args, **kwargs)
735
736

    def get(self, request, *args, **kwargs):
737
738
739
740
        context = super().get_context_data(**kwargs)
        user = self.request.user

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

743
        comments = Comment.objects.filter(materi__id__in=posts_data.keys()).order_by("-timestamp")
744
745
746
747
748
749
750

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

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

751
        return self.render_to_response(context=context)
752

753

754
755
756
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

757
    def dispatch(self, request, *args, **kwargs):
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
        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)

773
    def post(self, request, *args, **kwargs):
774
775
776
777
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
778
        form = UploadMateriForm(request.POST, request.FILES, instance=current_materi)
779
780
781
782
783
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.status = "REVISION"
            materi.save()
784
            kateg = form.cleaned_data["categories"]
785
786
787
788
789
790
791
792
793
            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)

794

Samuel Dimas's avatar
Samuel Dimas committed
795
796
797
798
799
800
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

801
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
802
803
804
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

805
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
806

807
        template = loader.get_template("error-404.html")
Samuel Dimas's avatar
Samuel Dimas committed
808
        return HttpResponse(template.render(context, request))
809
810


811
812
813
814
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

    def get_context_data(self, **kwargs):
815
        context = super(DownloadHistoryView, self).get_context_data(**kwargs)
816
817
818
819
820
821
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
822
            riwayat_list = current_user.riwayat_unduh.all().order_by("-timestamp")
823
824
825
            context["riwayat_list"] = riwayat_list
            context["user_name"] = current_user.name
        else:
826
827
828
            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")
829
            context["riwayat_list"] = riwayat_list
830
            context["user_name"] = "Guest"
831
        return self.render_to_response(context)
832

833

834
835
836
837
838
839
840
def upload_to_gdrive(file_path, title):
    gauth = GoogleAuth()
    gauth.LocalWebserverAuth()

    drive = GoogleDrive(gauth)
    file1 = drive.CreateFile()
    file1.SetContentFile(file_path)
841
842
    file1["title"] = title
    print("title: %s, mimeType: %s" % (file1["title"], file1["mimeType"]))
843
844
    file1.Upload()

845

846
847
848
849
850
851
852
853
854
855
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):
        with open(file_path, "rb") as fh:
            upload_to_gdrive(file_path, materi.title)
    else:
        raise Http404("File tidak dapat ditemukan.")

856
857
    return HttpResponseRedirect(reverse("detail-materi", kwargs={"pk": pk}))