Fakultas Ilmu Komputer UI

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

from django.conf import settings
5
from django.contrib.auth.models import AnonymousUser
Saul Andre's avatar
Saul Andre committed
6
from django.contrib import messages
7
from django.core import serializers
8
from django.core.exceptions import PermissionDenied
9
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
10
from django.db.models import Q
11
12
13
14
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
from django.shortcuts import get_object_or_404, redirect, render
from django.template import loader
15
from django.urls import reverse
igor lestin sianipar's avatar
igor lestin sianipar committed
16
from django.views.generic import TemplateView, ListView
17
18
19

from app.forms import SuntingProfilForm, UploadMateriForm
from app.models import Category, Comment, Materi, Like, ViewStatistics, DownloadStatistics
20
from authentication.models import User
21

22
23

class DaftarKatalog(TemplateView):
igor lestin sianipar's avatar
igor lestin sianipar committed
24
    paginate_by = 2
25
26
27
28
29
30
31
    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)
32
        context["kategori_list"] = Category.objects.all()
33
        try:
34
35
            context["materi_list"] = Materi.objects.all().filter(
                status="APPROVE")
36
37
        except:
            context["materi_list"] = None
38

39
        getSearch = request.GET.get('search')
40
        if getSearch:
41
            list = Materi.objects.filter(
42
                Q(title__icontains=getSearch) |
43
                Q(author__icontains=getSearch) |
44
45
                Q(uploader__name__icontains=getSearch) |
                Q(descriptions__icontains=getSearch) |
46
                Q(publisher__icontains=getSearch)
47
48
            ).distinct()
            context["materi_list"] = list.filter(status="APPROVE")
Saul Andre's avatar
Saul Andre committed
49

50
51
52
        getKategori = request.GET.get("kategori")
        if getKategori:
            pkGet = request.GET.get("kategori")
53
54
55
56
            kategori = Category.objects.get(pk=pkGet)
            list = Materi.objects.filter(categories=kategori.pk)
            context["materi_list"] = list.filter(status="APPROVE")

57
        getSort = request.GET.get("sort")
58
59
        if getSort:
            list = Materi.objects.all().filter(status="APPROVE")
60
61
62
63
64
65
            if(getSort == "judul"):
                context["materi_list"] = list.order_by('title')
            elif(getSort == "penulis"):
                context["materi_list"] = list.order_by('author')
            elif(getSort == "pengunggah"):
                context["materi_list"] = list.order_by('uploader')
66

67
68
        return self.render_to_response(context=context)

69

70
71
72
73
class DetailMateri(TemplateView):
    template_name = "app/detail_materi.html"

    def get_context_data(self, **kwargs):
74
75
76
77
78
79
80
81
82
        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
        context["has_liked"] = Like.objects.filter(
            materi=materi, session_id=self.request.session.session_key).exists()
        return context
83
84
85

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
86
87
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
88
        context["comment_data"] = query_set_for_comment
89
90
        return self.render_to_response(context=context)

91
92
    def get_user_name(self, request):
        user_name = ""
93
94
95
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
96
97
98
99
100
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

101
    def post(self, request, *args, **kwargs):
102
        commentText = request.POST.get("comment", None)
103
        if commentText == None or commentText == "":
104
105
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
106
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
107
108
            query_set_for_comment = Comment.objects.filter(
                materi=context["materi_data"])
109
            context["comment_data"] = query_set_for_comment
110
            return self.render_to_response(context=context)
111

112
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
113
        user_obj = request.user if request.user.is_authenticated else None
114
        print(user_obj)
115
116
        comment = Comment.objects.create(comment=commentText,
                                         username=self.get_user_name(request), materi=materi, user=user_obj)
117
118
119
        comment.save()
        return HttpResponseRedirect(request.path)

120

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
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"})


142
143
144
145
146
147
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)

148

149
150
151
152
153
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):
154
155
156
157
158
159
160
161
162
163
        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)
                DownloadStatistics(materi=materi).save()
                return response
        except Exception as e:
            raise Http404("File tidak dapat ditemukan.")
164
165
166
    else:
        raise Http404("File tidak dapat ditemukan.")

167

168
169
170
171
172
173
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)
174
175
176
177
178
179
180
181
182
        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.")
183
184
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
185

186

igor lestin sianipar's avatar
igor lestin sianipar committed
187
class UploadMateriView(TemplateView):
188
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
189
190
191
192
193
194
    context = {}

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

Saul Andre's avatar
Saul Andre committed
195
    def post(self, request, *args, **kwargs):
igor lestin sianipar's avatar
igor lestin sianipar committed
196
197
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
198
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
199
200
201
202
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.save()
203
204
205
            kateg = form.cleaned_data['categories']
            for i in kateg:
                materi.categories.add(i)
206
207
208

            messages.success(
                request, "Materi berhasil diunggah, periksa riwayat unggah anda")
209
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
210
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
211
            context = self.get_context_data(**kwargs)
212
            context["form"] = form
Saul Andre's avatar
Saul Andre committed
213
            messages.error(request, "Terjadi kesalahan pada pengisian data")
igor lestin sianipar's avatar
igor lestin sianipar committed
214
215
216
217
218
219
            return self.render_to_response(context)

    def get(self, request, *args, **kwargs):
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
        context = self.get_context_data(**kwargs)
220
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
221
        return self.render_to_response(context)
222

Samuel Dimas's avatar
Samuel Dimas committed
223

224
225
226
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
227

228
229
230
231
232
233
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


234
class DashboardKontributorView(TemplateView):
235
    template_name = "dashboard.html"
236
237
238
239
240
241
242

    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):
243
244
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
245
246
247
248
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
249
250
251
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
252
        return self.render_to_response(context)
253

254

255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
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)
272

273

274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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)

292

293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
class SuntingProfilView(TemplateView):
    template_name = "sunting.html"

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_contributor:
            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
311
        context["form"] = SuntingProfilForm(instance=current_user)
312
313
314
315
316
317
        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
318
        current_user = self.request.user
319
320
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
321
        if form.is_valid():
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
322
            form.save()
323
324
325
326
327
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
328

329

330
331
332
333
334
335
336
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)
337

338
    def get_context_data(self, **kwargs):
339
340
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
341
342
343
344
345
346
347
348
349
350
        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)

351

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

360
361
362
363
364
365
366
367
368
369
370
371
    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)

372

Samuel Dimas's avatar
Samuel Dimas committed
373
374
375
376
377
378
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

379
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
380
381
382
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

383
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
384

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