Fakultas Ilmu Komputer UI

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

from django.conf import settings
5
from django.contrib.auth.models import AnonymousUser
6
from django.core import serializers
7
from django.core.exceptions import PermissionDenied
8
from django.db.models import Q
9
10
11
12
13
from django.http import (Http404, HttpResponse, HttpResponseRedirect,
                         JsonResponse)
from django.shortcuts import get_object_or_404, redirect, render
from django.template import loader
from django.views.generic import TemplateView
14
15
16
17
18

from authentication.models import User

from .forms import SuntingProfilForm, UploadMateriForm
from .models import Category, Comment, Materi
igor lestin sianipar's avatar
igor lestin sianipar committed
19

20
21
22
23
24
25
26
27
28

class DaftarKatalog(TemplateView):
    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)
29
        context["kategori_list"] = Category.objects.all()
30
        try:
31
32
            context["materi_list"] = Materi.objects.all().filter(
                status="APPROVE")
33
34
        except:
            context["materi_list"] = None
35

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

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

54
        getSort = request.GET.get("sort")
55
56
        if getSort:
            list = Materi.objects.all().filter(status="APPROVE")
57
58
59
60
61
62
            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')
63

64
65
        return self.render_to_response(context=context)

66

67
68
69
70
71
72
73
74
class DetailMateri(TemplateView):
    template_name = "app/detail_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)
75
        context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
76
77
        query_set_for_comment = Comment.objects.filter(
            materi=context["materi_data"])
78
        context["comment_data"] = query_set_for_comment
79
80
        return self.render_to_response(context=context)

81
82
    def get_user_name(self, request):
        user_name = ""
83
84
85
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
86
87
88
89
90
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

91
    def post(self, request, *args, **kwargs):
92
        commentText = request.POST.get("comment", None)
93
        if commentText == None or commentText == "":
94
95
            context = self.get_context_data(*args, **kwargs)
            context["error_message"] = "Anda belum menuliskan komentar"
96
            context["materi_data"] = get_object_or_404(Materi, pk=kwargs["pk"])
97
98
            query_set_for_comment = Comment.objects.filter(
                materi=context["materi_data"])
99
            context["comment_data"] = query_set_for_comment
100
            return self.render_to_response(context=context)
101

102
        materi = get_object_or_404(Materi, pk=kwargs["pk"])
103
104
105
        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)
106
107
108
        comment.save()
        return HttpResponseRedirect(request.path)

109

110
111
112
113
114
115
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)

116

117
118
119
120
121
122
123
124
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):
        mimetype = mimetypes.guess_type(file_path)
        with open(file_path, "rb") as fh:
            response = HttpResponse(fh.read(), content_type=mimetype[0])
125
126
            response["Content-Disposition"] = "attachment; filename=" + \
                os.path.basename(file_path)
127
128
129
130
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")

131

132
133
134
135
136
137
138
139
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)
        with open(file_path, "rb") as fh:
            response = HttpResponse(fh.read(), content_type=mimetype[0])
140
141
            response["Content-Disposition"] = "inline; filename=" + \
                os.path.basename(file_path)
142
143
144
            return response
    else:
        raise Http404("File tidak dapat ditemukan.")
igor lestin sianipar's avatar
igor lestin sianipar committed
145
146
147


class UploadMateriView(TemplateView):
148
    template_name = "unggah.html"
igor lestin sianipar's avatar
igor lestin sianipar committed
149
150
151
152
153
154
    context = {}

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

Saul Andre's avatar
Saul Andre committed
155
    def post(self, request, *args, **kwargs):
igor lestin sianipar's avatar
igor lestin sianipar committed
156
157
        if request.user.is_authenticated == False:
            raise PermissionDenied(request)
158
        form = UploadMateriForm(request.POST, request.FILES)
igor lestin sianipar's avatar
igor lestin sianipar committed
159
160
161
162
        if form.is_valid():
            materi = form.save(commit=False)
            materi.uploader = request.user
            materi.save()
163
            return HttpResponseRedirect("/unggah/")
Saul Andre's avatar
Saul Andre committed
164
        else:
igor lestin sianipar's avatar
igor lestin sianipar committed
165
            context = self.get_context_data(**kwargs)
166
            context["form"] = form
igor lestin sianipar's avatar
igor lestin sianipar committed
167
168
169
170
171
172
            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)
173
        context["form"] = UploadMateriForm
igor lestin sianipar's avatar
igor lestin sianipar committed
174
        return self.render_to_response(context)
175

Samuel Dimas's avatar
Samuel Dimas committed
176

177
178
179
class UploadMateriHTML(TemplateView):
    template_name = "unggah.html"
    context = {}
180

181
182
183
184
185
186
    def get_template_names(self):
        if self.request.path == "/unggah/":
            template_name = "unggah.html"
        return template_name


187
class DashboardKontributorView(TemplateView):
188
    template_name = "dashboard.html"
189
190
191
192
193
194
195

    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):
196
197
        context = super(DashboardKontributorView,
                        self).get_context_data(**kwargs)
198
199
200
201
        return context

    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
202
203
204
        current_user = self.request.user
        materi_list = current_user.materi_set.all()
        context["materi_list"] = materi_list
205
        return self.render_to_response(context)
206

207

208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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)

226

227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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
245
        context["form"] = SuntingProfilForm(instance=current_user)
246
247
248
249
250
251
        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
252
        current_user = self.request.user
253
254
        form = SuntingProfilForm(
            request.POST, request.FILES, instance=current_user)
255
        if form.is_valid():
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
256
            form.save()
257
258
259
260
261
            return HttpResponseRedirect("/profil/")
        else:
            context = self.get_context_data(**kwargs)
            context["form"] = form
            return self.render_to_response(context)
262

263

264
265
266
267
268
269
270
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)
271

272
    def get_context_data(self, **kwargs):
273
274
        context = super(SuksesLoginKontributorView,
                        self).get_context_data(**kwargs)
275
276
277
278
279
280
281
282
283
284
        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)

285

286
287
288
289
290
291
292
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)
293

294
295
296
297
298
299
300
301
302
303
304
305
    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)

306

Samuel Dimas's avatar
Samuel Dimas committed
307
308
309
310
311
312
def pages(request):
    context = {}
    # All resource paths end in .html.
    # Pick out the html file name from the url. And load that template.
    try:

313
        load_template = request.path.split("/")[-1]
Samuel Dimas's avatar
Samuel Dimas committed
314
315
316
        template = loader.get_template(load_template)
        return HttpResponse(template.render(context, request))

317
    except Exception as e:
Samuel Dimas's avatar
Samuel Dimas committed
318

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