Fakultas Ilmu Komputer UI

views.py 29.6 KB
Newer Older
1
2
3
4
import mimetypes
import os

from django.conf import settings
5
from django.contrib import messages
6
from django.contrib.auth.models import AnonymousUser
7
from django.core.exceptions import PermissionDenied, ValidationError
8
from django.core.paginator import Paginator
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.shortcuts import get_object_or_404, redirect
13
from django.template import loader
14
15
from django.views.generic import TemplateView

16
from administration.models import VerificationReport
17
18
19
from app.forms import SuntingProfilForm, UploadMateriForm, RatingContributorForm
from app.models import Category, Comment, Materi, Like, ViewStatistics, DownloadStatistics, ReqMaterial, Rating, \
    RatingContributor
20
from app.utils.fileManagementUtil import get_random_filename, remove_image_exifdata
21
from authentication.models import User
22
import django
23
24
import pandas as pd
from io import BytesIO
25
from django.contrib import messages
26

27
28

class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
29
    paginate_by = 2
30
31
32
33
34
35
36
    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)
37
        context["kategori_list"] = Category.objects.all()
38

Mika dabelza abi's avatar
Mika dabelza abi committed
39
        lstMateri = Materi.objects.filter(status="APPROVE").order_by("date_modified")
Mika dabelza abi's avatar
Mika dabelza abi committed
40
41
        url = ""

42
        getSearch = request.GET.get('search')
43
        if getSearch:
Mika dabelza abi's avatar
Mika dabelza abi committed
44
            url = url + "&search={0}".format(getSearch)
Mika dabelza abi's avatar
Mika dabelza abi committed
45
            lstMateri = lstMateri.filter(
46
                Q(title__icontains=getSearch) |
47
                Q(author__icontains=getSearch) |
48
49
                Q(uploader__name__icontains=getSearch) |
                Q(descriptions__icontains=getSearch) |
50
                Q(publisher__icontains=getSearch)
51
            ).distinct()
Saul Andre's avatar
Saul Andre committed
52

53
54
        getKategori = request.GET.get("kategori")
        if getKategori:
Mika dabelza abi's avatar
Mika dabelza abi committed
55
56
            url = url + "&kategori={0}".format(getKategori)
            kategori = Category.objects.get(pk=getKategori)
Mika dabelza abi's avatar
Mika dabelza abi committed
57
            lstMateri = lstMateri.filter(categories=kategori.pk)
58

59
        getSort = request.GET.get("sort")
60
        if getSort:
Mika dabelza abi's avatar
Mika dabelza abi committed
61
            url = url + "&sort={0}".format(getSort)
62
            if(getSort == "judul"):
Mika dabelza abi's avatar
Mika dabelza abi committed
63
                lstMateri = lstMateri.order_by('title')
64
            elif(getSort == "penulis"):
Mika dabelza abi's avatar
Mika dabelza abi committed
65
                lstMateri = lstMateri.order_by('author')
66
            elif(getSort == "pengunggah"):
Mika dabelza abi's avatar
Mika dabelza abi committed
67
                lstMateri = lstMateri.order_by('uploader')
Mika dabelza abi's avatar
Mika dabelza abi committed
68
            elif(getSort == "terbaru"):
Mika dabelza abi's avatar
Mika dabelza abi committed
69
                lstMateri = lstMateri.order_by('-date_created')
Mika dabelza abi's avatar
Mika dabelza abi committed
70
            elif(getSort == "terlama"):
71
                lstMateri = lstMateri.order_by('date_created')
Mika dabelza abi's avatar
Mika dabelza abi committed
72
            elif(getSort == "terpopuler"):
Mika dabelza abi's avatar
Mika dabelza abi committed
73
                lstMateri = lstMateri.annotate(count=Count('like__id')).order_by('-count')
74

Mika dabelza abi's avatar
Mika dabelza abi committed
75
        context["materi_list"] = lstMateri
Mika dabelza abi's avatar
Mika dabelza abi committed
76
77
78
79
80
81
        paginator = Paginator(context["materi_list"], 15)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        context["materi_list"] = page_obj

        context["url"] = url
82
83
        return self.render_to_response(context=context)

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class KatalogPerKontributorView(TemplateView):
    template_name = "app/katalog_kontri.html"
    
    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)
         
        materi_list = Materi.objects.filter(status="APPROVE", uploader=context["contributor"]).order_by("date_modified")
                    
        paginator = Paginator(materi_list, 15)
        page_number = request.GET.get('page')
        materi_list_by_page = paginator.get_page(page_number)
        context["materi_list"] = materi_list_by_page
102
103
        contributor = get_object_or_404(User, email=kwargs["email"])
        context["form_rating"] = RatingContributorForm(initial={'user': contributor})
104
        return self.render_to_response(context=context)
105

106
107
108
109
110
111
    def post(self, request, *args, **kwargs):
        data = RatingContributorForm(request.POST)
        if data.is_valid():
            data.save()
        return redirect('katalog-per-kontributor', email=kwargs['email'])

112
113
114
115
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
116
117
118
119
120
121
        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
122
        context["report"] = VerificationReport.objects.filter(materi=materi)
123
124
        context["has_liked"] = Like.objects.filter(
            materi=materi, session_id=self.request.session.session_key).exists()
125
126
127
128
        publishedDate = ''
        if(materi.published_date == None):
            publishedDate = 'n.d'
        else :
129
            publishedDate = materi.published_date.strftime('%Y-%m-%d %H:%M')
130
131
        citationAPA = materi.author+' . ('  + publishedDate +') . ' + materi.title +' . '+materi.publisher
        context["citationAPA"] = citationAPA
132
133
134
135
136
137
138
        context['materi_rating_score'] = 0

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

139
        return context
140
141
142

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
143
144
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
145
        context["comment_data"] = query_set_for_comment
146
147
        return self.render_to_response(context=context)

148
149
    def get_user_name(self, request):
        user_name = ""
150
151
152
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
153
154
155
156
157
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

158
    def post(self, request, *args, **kwargs):
159
        commentText = request.POST.get("comment", None)
160
        if commentText == None or commentText == "":
161
162
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
163
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
164
165
            query_set_for_comment = Comment.objects.filter(
                materi=context["materi_data"])
166
            context["comment_data"] = query_set_for_comment
167
            return self.render_to_response(context=context)
168

169
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
170
171
172
        user_obj = request.user if request.user.is_authenticated else None
        comment = Comment.objects.create(comment=commentText,
                                         username=self.get_user_name(request), materi=materi, user=user_obj)
173
174
175
        comment.save()
        return HttpResponseRedirect(request.path)

176

177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def toggle_like(request):
    if request.method == 'POST':
        materi_id = request.POST.get('materi_id', None)
        session_id = request.POST.get('session_id', None)
        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)
        has_liked = Like.objects.filter(
            materi=materi, session_id=session_id).exists()
        if has_liked:
            like = get_object_or_404(
                Like, materi=materi, session_id=session_id)
            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"})


198
199
200
201
202
203
def delete_comment(request, pk_materi, pk_comment):
    comment = get_object_or_404(Comment, pk=pk_comment)
    url = '/materi/' + str(pk_materi) + "/"
    comment.delete()
    return HttpResponseRedirect(url)

204

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def add_rating_materi(request):
    if request.method == 'POST' and request.user.is_authenticated:

        materi_id = request.POST.get('materi_id', None)
        rating_score = request.POST.get('rating_score', None)

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


240
241
242
243
244
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):
245
246
247
248
249
250
        try:
            mimetype = mimetypes.guess_type(file_path)
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
                response["Content-Disposition"] = "attachment; filename=" + \
                    os.path.basename(file_path)
251
252
253
254
255
256
257
258
                if request.user.is_authenticated:
                    DownloadStatistics(materi=materi, downloader=request.user).save()
                else:
                    downloaded_materi = DownloadStatistics.objects.create(materi=materi)
                    if 'downloaded_materi' not in request.session:
                        request.session['downloaded_materi'] = []
                    request.session['downloaded_materi'].append(downloaded_materi.pk)
                    request.session.modified = True
259
260
261
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
262
263
264
    else:
        raise Http404("File tidak dapat ditemukan.")

igor lestin sianipar's avatar
igor lestin sianipar committed
265

266
267
268
269
270
271
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)
272
273
274
275
276
277
278
279
280
        try:
            with open(file_path, "rb") as fh:
                response = HttpResponse(fh.read(), content_type=mimetype[0])
                response["Content-Disposition"] = "inline; filename=" + \
                    os.path.basename(file_path)
                ViewStatistics(materi=materi).save()
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
281
282
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
283

igor lestin sianipar's avatar
igor lestin sianipar committed
284

igor lestin sianipar's avatar
igor lestin sianipar committed
285
class UploadMateriView(TemplateView):
286
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
287
288
289
290
291
292
    context = {}

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

Saul Andre's avatar
Saul Andre committed
293
    def post(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
294
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
295
            raise PermissionDenied(request)
296
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
297
298
299
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
300
301
302
303
304
305
            konten = form.cleaned_data['content']
            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
306
            materi.save()
307
308
309
            kateg = form.cleaned_data['categories']
            for i in kateg:
                materi.categories.add(i)
igor lestin sianipar's avatar
igor lestin sianipar committed
310
311
            messages.success(
                request, "Materi berhasil diunggah, periksa riwayat unggah anda")
312
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
313
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
314
            context = self.get_context_data(**kwargs)
315
            context["form"] = form
316
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
317
318
319
            return self.render_to_response(context)

    def get(self, request, *args, **kwargs):
Steven Kusuman's avatar
Steven Kusuman committed
320
        if request.user.is_authenticated == False or not request.user.is_contributor:
igor lestin sianipar's avatar
igor lestin sianipar committed
321
            raise PermissionDenied(request)
Steven Kusuman's avatar
Steven Kusuman committed
322
        
igor lestin sianipar's avatar
igor lestin sianipar committed
323
        context = self.get_context_data(**kwargs)
324
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
325
        return self.render_to_response(context)
326

327
328
329
330
331
    def validate_file_extension(self, value):
        ext = os.path.splitext(value.name)[1]  # [0] returns path+filename
        valid_extensions = ['.pdf', '.doc', '.docx', '.jpg', '.png', '.xlsx', '.xls', '.mp4', '.mp3']
        if not ext.lower() in valid_extensions:
            raise ValidationError('Unsupported file extension.')
332

Samuel Dimas's avatar
Samuel Dimas committed
333

334
335
336
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
igor lestin sianipar's avatar
igor lestin sianipar committed
337

338
339
340
341
342
343
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
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):

        if 'template' in self.request.GET:

            data_frame = pd.DataFrame({
                'Title': [],
                'Author': [],
                'Publisher': [],
                'Categories': [],
                'Description': [],
            })

            with BytesIO() as b:
                writer = pd.ExcelWriter(b, engine='xlsxwriter') #pylint: disable=abstract-class-instantiated
                data_frame.to_excel(writer, index=0)
                writer.save()
                response = HttpResponse(
                        b.getvalue(), 
                        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

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

        row,lines = excel.shape
        categories = Category.objects.all()
        
        field_length = {
            'title' : 50,
            'author' : 30,
            'publisher' : 30,
        }

        message = None

        # First pass, validate input
        for i in range(row):
            
            # Validate Categories
            for c in excel['Categories'][i].split(","):
                sel_cat = categories.filter(name=c)
                if sel_cat.count() == 0:
                    message = f"Kategori %s tidak ditemukan" % c
                    break

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

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

            if len(excel['Publisher'][i]) > field_length['publisher']:
                message = f"Publisher maksimal %d karakter" % field_length['publisher']

            if message != None:
                break
            
        if message != None:
            messages.error(request, message)
            return HttpResponseRedirect('/unggah_excel/')

        # Second pass, save data
        with django.db.transaction.atomic():
            for i in range(row):
                materi = Materi(
                            title=excel['Title'][i],
                            author=excel['Author'][i],
                            publisher=excel['Publisher'][i],
                            descriptions=excel['Description'][i],
                            uploader=request.user
                        )
                materi.save()
                
                for c in excel['Categories'][i].split(","):
                    materi.categories.add(categories.get(name=c))

        messages.success(request, 'Materi berhasil diunggah')

        return HttpResponseRedirect('/unggah_excel/')


443
class DashboardKontributorView(TemplateView):
444
    template_name = "dashboard.html"
445
446
447
448
449
450
451

    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):
452
453
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
454
455
456
457
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
458
459
460
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
461
        return self.render_to_response(context)
462

463

464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
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)
481

482

483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
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)

501

502
503
504
505
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
506
        if not request.user.is_authenticated or not request.user.is_contributor:
507
508
509
510
511
512
513
514
515
516
517
518
519
            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
520
        context["form"] = SuntingProfilForm(instance=current_user)
521
522
523
524
525
526
        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
527
        current_user = self.request.user
528

529
530
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
531
        if form.is_valid():
532
            current_user.default_profile_picture = True
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547

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

                form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
                form.save()

                remove_image_exifdata(f_path)
            else: 
                form.save()
548
549
550
551
552
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
553

igor lestin sianipar's avatar
igor lestin sianipar committed
554

555
556
557
558
559
560
561
562
563
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):
igor lestin sianipar's avatar
igor lestin sianipar committed
564
565
        context = super(SuntingProfilAdminView,
                        self).get_context_data(**kwargs)
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        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
582

583
584
585
586
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
        if form.is_valid():
            current_user.default_profile_picture = True
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601

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

                form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
                form.save()

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

608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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):
        context = super(ReqMateriView,
                        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)
        if title is None:
            return JsonResponse({"success": False, "msg": "Missing parameter"})
        ReqMaterial(title=title).save()
        return JsonResponse({"success": True, "msg": "Permintaan materi berhasil dikirimkan"})

632

633
634
635
636
637
638
639
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)
640

641
    def get_context_data(self, **kwargs):
642
643
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
644
645
646
647
648
649
650
651
652
653
        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)

654

655
656
657
658
659
660
661
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)
662

663
664
665
666
667
668
669
670
671
672
673
674
    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
675

676
677
678
class PostsView(TemplateView):

    template_name = "user_uploaded_posts.html"
679
680

    def dispatch(self, request, *args, **kwargs):
681
        if not request.user.is_authenticated:
682
            raise PermissionDenied(request)
683
        return super(PostsView, self).dispatch(request, *args, **kwargs)
684
685

    def get(self, request, *args, **kwargs):
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
        context = super().get_context_data(**kwargs)
        user = self.request.user

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

        comments = Comment.objects \
            .filter(materi__id__in=posts_data.keys()) \
            .order_by("-timestamp")

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

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

702
        return self.render_to_response(context=context)
703

704

705
706
707
class RevisiMateriView(TemplateView):
    template_name = "revisi.html"

708
    def dispatch(self, request, *args, **kwargs):
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
        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)

    def post(self,request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)

        current_materi = get_object_or_404(Materi, pk=kwargs["pk"])
        form = UploadMateriForm(
            request.POST, request.FILES, instance=current_materi)
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.status = "REVISION"
            materi.save()
            kateg = form.cleaned_data['categories']
            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)

Samuel Dimas's avatar
Samuel Dimas committed
746
747
748
749
750
751
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

752
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
753
754
755
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

756
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
757

758
        template = loader.get_template("error-404.html")
Samuel Dimas's avatar
Samuel Dimas committed
759
        return HttpResponse(template.render(context, request))
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
		
class DownloadHistoryView(TemplateView):
    template_name = "download_history.html"

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

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        if request.user.is_authenticated:
            current_user = self.request.user
            riwayat_list = current_user.riwayat_unduh.all().order_by('-timestamp')
            context["riwayat_list"] = riwayat_list
            context["user_name"] = current_user.name
        else:
            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')
            context["riwayat_list"] = riwayat_list
            context["user_name"] = 'Guest'
        return self.render_to_response(context)