Fakultas Ilmu Komputer UI

services.py 18.7 KB
Newer Older
1
2
3
import datetime
import os
import random
Arief Pratama's avatar
Arief Pratama committed
4
import shutil
5
from functools import cmp_to_key
6

7
8
9
import requests
from administration.models import VerificationReport
from digipus import settings
10
11
12
from django.contrib import messages
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
13
from django.db.models import Case, Count, Q, When
14
from django.shortcuts import get_object_or_404
15
from django.utils import timezone
16
17
18
19
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

from app.forms import SuntingProfilForm
20
21
22
23
24
from app.models import (Category, Comment, DislikeComment, DownloadStatistics,
                        Like, LikeComment, Materi, Rating, ReadLater,
                        ViewStatistics)
from app.utils.fileManagementUtil import (get_random_filename,
                                          remove_image_exifdata)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67


class DafterKatalogService:

    @staticmethod
    def search_materi(get_search, lst_materi, url):
        url = url + "&search={0}".format(get_search)
        lst_materi = (
            lst_materi.search(get_search)
                .filter(
                Q(author__icontains=get_search)
                | Q(uploader__name__icontains=get_search)
                | Q(descriptions__icontains=get_search)
                | Q(publisher__icontains=get_search)
            )
                .distinct()
        )
        return lst_materi, url

    @staticmethod
    def filter_materi_by_kategori(get_kategori, lst_materi, url):
        url = url + "&kategori={0}".format(get_kategori)
        kategori = Category.objects.get(pk=get_kategori)
        lst_materi = lst_materi.filter(categories=kategori.pk)
        return lst_materi, url

    @staticmethod
    def apply_sort(get_sort, lst_materi, url):
        url = url + "&sort={0}".format(get_sort)
        if (get_sort == "judul"):
            lst_materi = lst_materi.order_by('title')
        elif (get_sort == "penulis"):
            lst_materi = lst_materi.order_by('author')
        elif (get_sort == "pengunggah"):
            lst_materi = lst_materi.order_by('uploader')
        elif (get_sort == "terbaru"):
            lst_materi = lst_materi.order_by('-date_created')
        elif (get_sort == "terlama"):
            lst_materi = lst_materi.order_by('date_created')
        elif (get_sort == "terpopuler"):
            lst_materi = lst_materi.annotate(count=Count('like__id')).order_by('-count')
        elif (get_sort == "jumlah_unduh"):
            lst_materi = lst_materi.annotate(count=Count('unduh__id')).order_by('-count')
68
69
        elif (get_sort == "jumlah_tampilan"):
            lst_materi = lst_materi.annotate(count=Count('baca__id')).order_by('-count')
70
71
        elif (get_sort == "jumlah_komentar"):
            lst_materi = lst_materi.annotate(count=Count('comment__id')).order_by('-count')
72
73
74
75
76
        return lst_materi, url

    @staticmethod
    def apply_options(lst_materi, request, url):
        should_random = bool(request.GET.get("random"))
77
78
        should_get_recommendation = bool(request.GET.get("recommendation"))

79
80
81
82
83
84
85
86
87
        get_search = request.GET.get("search")
        if get_search:
            lst_materi, url = DafterKatalogService.search_materi(get_search, lst_materi, url)
        get_kategori = request.GET.get("kategori")
        if get_kategori:
            lst_materi, url = DafterKatalogService.filter_materi_by_kategori(get_kategori, lst_materi, url)
        get_sort = request.GET.get("sort")
        if get_sort:
            lst_materi, url = DafterKatalogService.apply_sort(get_sort, lst_materi, url)
88
89
90
91

        if should_get_recommendation:
            lst_materi = DafterKatalogService.get_recommendation(lst_materi)
        elif should_random:
92
            lst_materi = DafterKatalogService.apply_random(lst_materi)
93

94
95
        return lst_materi, url

96
97
98
99
100
101
102
103
104
105
    @staticmethod
    def get_recommendation(lst_materi):
        sorted_list = sorted(
            lst_materi,
            key=cmp_to_key(lambda a, b: 1 if (a.like_count, a.date_modified) < (b.like_count, b.date_modified) else -1),
        )
        ids = [materi.id for materi in sorted_list]
        preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)])
        return Materi.objects.filter(id__in=ids).order_by(preserved)

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    @staticmethod
    def apply_random(lst_materi):
        return random.sample(list(lst_materi), len(lst_materi))


class DetailMateriService:

    @staticmethod
    def init_context_data(context, materi, session):
        context["session_id"] = session.session_key
        context["materi_data"] = materi
        context["report"] = VerificationReport.objects.filter(materi=materi)
        context["has_liked"] = Like.objects.filter(materi=materi, session_id=session.session_key).exists()


    @staticmethod
    def set_published_date(materi):
        published_date = ""
        if materi.published_date == None:
            published_date = "n.d"
        else:
            published_date = materi.published_date.strftime("%Y-%m-%d %H:%M")
        return published_date


    @staticmethod
    def init_citation_and_materi_rating(context, materi, published_date, request):
        citation_apa = materi.author + " . (" + published_date + ") . " + materi.title + " . " + materi.publisher
        context["citationAPA"] = citation_apa
        context["citationIEEE"] = CitationService.get_citation_ieee(request, materi)
        context["materi_rating_score"] = 0

    @staticmethod
    def find_comment_like_dislike(query_set_for_comment, session):
        has_liked = {}
        has_disliked = {}
        for comment in query_set_for_comment:
            has_liked[comment.id] = LikeComment.objects.filter(comment=comment,
                                                               session_id=session.session_key).exists()
            has_disliked[comment.id] = DislikeComment.objects.filter(comment=comment,
                                                                     session_id=session.session_key).exists()
        return has_disliked, has_liked

    @staticmethod
    def get_user_name(request):
        user_name = ""
        if isinstance(request.user, AnonymousUser):
            user_name = "Anonim"
        elif request.user.is_admin:
            user_name = "Admin"
        elif request.user.is_contributor:
            user_name = request.user.name
        return user_name

160
161
162
163
    @staticmethod
    def init_materi_download_count(context, materi):
        context["materi_download_count"] = materi.unduh.all().count()

164
165
166
167
class CitationService:

    @staticmethod
    def get_citation_ieee(request, materi):
168
        current_date = timezone.now()
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
        current_day = str(current_date.day)
        current_month = current_date.strftime("%b")
        current_year = str(current_date.year)
        published_date = CitationService._get_ieee_publish_date(materi)

        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):
                if j < (len(author_name_split) - 1):
                    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 + ", "

        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()
        )
        return citation_result

    @staticmethod
    def _get_ieee_publish_date(materi):
        if materi.published_date == None:
            published_date = "n.d"
        else:
            published_date = materi.published_date.strftime("%Y")
        return published_date

class LikeDislikeService:

    @staticmethod
    def apply_like_materi(materi_id, session_id):
        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()
            response = {"success": True, "liked": True}
        else:
            Like(materi=materi, session_id=session_id).save()
            response = {"success": True, "liked": False}
        return response


    @staticmethod
    def apply_comment_like(comment_id, session_id):
        comment = get_object_or_404(Comment, pk=comment_id)
        has_liked = LikeComment.objects.filter(comment=comment, session_id=session_id).exists()
        if has_liked:
            like = get_object_or_404(LikeComment, comment=comment, session_id=session_id)
            like.delete()
            response = {"success": True, "liked": True, "comment_id": comment_id}
        else:
            LikeComment(comment=comment, session_id=session_id).save()
            response = {"success": True, "liked": False, "comment_id": comment_id}
        return response


    @staticmethod
    def apply_comment_dislike(comment_id, session_id):
        comment = get_object_or_404(Comment, pk=comment_id)
        has_disliked = DislikeComment.objects.filter(comment=comment, session_id=session_id).exists()
        if has_disliked:
            dislike = get_object_or_404(DislikeComment, comment=comment, session_id=session_id)
            dislike.delete()
            response = ({"success": True, "disliked": True, "comment_id": comment_id})
        else:
            DislikeComment(comment=comment, session_id=session_id).save()
            response = ({"success": True, "disliked": False, "comment_id": comment_id})
        return response


class MateriFieldValidationHelperService:

    @staticmethod
    def validate_materi_rating_params(materi_id, rating_score):
        if materi_id is None or rating_score is None:
            response = {"success": False, "msg": "Missing param"}
            status_code = 422
            is_valid = False
            return is_valid, materi_id, rating_score, response, status_code
        try:
            rating_score = int(rating_score)
        except ValueError:
            response = {"success": False, "msg": "rating_score must be an integer"}
            status_code = 422
            is_valid = False
            return is_valid, materi_id, rating_score, response, status_code
        try:
            materi_id = int(materi_id)
        except ValueError:
            response = {"success": False, "msg": "materi_id must be an integer"}
            status_code = 422
            is_valid = False
            return is_valid, materi_id, rating_score, response, status_code
        if rating_score not in range(1, 6):
            response = {"success": False, "msg": "Rating must be an integer from 1 to 5"}
            status_code = 422
            is_valid = False
            return is_valid, materi_id, rating_score, response, status_code
        return True, materi_id, rating_score, {}, 200



    @staticmethod
    def validate_materi_rating(materi_id, user):
        materi = Materi.objects.filter(pk=materi_id).first()
        if materi is None:
            response = {"success": False, "msg": "Materi does not exist"}
            status_code = 422
            is_valid = False
            return is_valid, materi, response, status_code
        if Rating.objects.filter(materi=materi, user=user).first() is not None:
            response = {"success": False, "msg": "Rating already exist"}
            status_code = 409
            is_valid = False
            return is_valid, materi, response, status_code
        return True, materi, {}, 201



class DownloadViewMateriHelperService:

    @staticmethod
    def build_materi_response(fh, file_path, materi, mimetype, request, response):
        response["Content-Disposition"] = "attachment; filename=" + os.path.basename(file_path)
        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
        return response

    @staticmethod
    def build_view_materi_response(file_path, materi, response):
        response["Content-Disposition"] = "inline; filename=" + os.path.basename(file_path)
        ViewStatistics(materi=materi).save()


class UploadMateriService:

    @staticmethod
    def validate_extension(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.")

    @staticmethod
339
    def validate_file_extension(konten, request, yt_video_id):
340
341
342
        is_file_extension_valid = True
        try:
            UploadMateriService.validate_extension(konten)
343
344
345
            UploadMateriService.validate_yt_video_url(yt_video_id)
        except ValidationError as e:
            messages.error(request, "Materi gagal diunggah, format file tidak sesuai"+str(e))
346
347
            is_file_extension_valid = False
        return is_file_extension_valid
348
349
350
351
352
353
354
        
    @staticmethod
    def validate_yt_video_url(value):
        r = requests.get('http://www.youtube.com/watch?v='+value)
        if "\"playabilityStatus\":{\"status\":\"ERROR\"" in r.text:
            raise ValidationError("Invalid Youtube video ID")
    
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
    @staticmethod
    def upload_materi(form, materi):
        materi.save()
        kateg = form.cleaned_data["categories"]
        for i in kateg:
            materi.categories.add(i)


    @staticmethod
    def validate_excel_categories(categories, excel, i, message):
        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
        return message


    @staticmethod
    def validate_excel_field_length(excel, field_length, i, message):
        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"]
        return message

    @staticmethod
    def upload_materi_excel(categories, excel, request, row):
Arief Pratama's avatar
Arief Pratama committed
385
386
        default_cover = 'book-cover-placeholder.png'

387
388
389
390
391
392
393
394
        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,
            )
Arief Pratama's avatar
Arief Pratama committed
395
396
397
398
399
400
401
402
403
404

            materi.cover.name = default_cover
            materi.content.name = default_cover

            # Check if file exists in /media
            if not os.path.exists(os.path.join(settings.MEDIA_ROOT, default_cover)):
                shutil.copy(
                    os.path.join('app','static','images',default_cover), 
                    os.path.join(settings.MEDIA_ROOT,default_cover))

405
406
407
408
409
            materi.save()

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

Arief Pratama's avatar
Arief Pratama committed
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
class EditProfileService:

    @staticmethod
    def update_profile_picture(current_user, request):
        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)

class RevisiMateriService:

    @staticmethod
    def revisi_materi(form, request):
        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()


class DownloadHistoryService:

    @staticmethod
    def get_riwayat_as_guest(request):
        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")
        return riwayat_list

    @staticmethod
    def get_riwayat_authenticated_user(current_user):
        riwayat_list = current_user.riwayat_unduh.all().order_by("-timestamp")
        return riwayat_list

    @staticmethod
    def init_data_guest_user(context, request):
        riwayat_list = DownloadHistoryService.get_riwayat_as_guest(request)
        context["riwayat_list"] = riwayat_list
        context["user_name"] = "Guest"

    @staticmethod
    def init_data_authenticated_user(context, current_user):
        riwayat_list = DownloadHistoryService.get_riwayat_authenticated_user(current_user)
        context["riwayat_list"] = riwayat_list
        context["user_name"] = current_user.name


class GoogleDriveUploadService:

    @staticmethod
    def upload_to_gdrive(file_path, title):
        gauth = GoogleAuth()
        gauth.LocalWebserverAuth()

        drive = GoogleDrive(gauth)
        file1 = drive.CreateFile()
        file1.SetContentFile(file_path)
        file1["title"] = title
        print("title: %s, mimeType: %s" % (file1["title"], file1["mimeType"]))
        file1.Upload()
Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490

class ReadLaterService:
    
    @staticmethod
    def toggle_read_later(materi_id, current_user):
        materi = get_object_or_404(Materi, pk=materi_id)
        read_later_item_exist = ReadLater.objects.filter(materi=materi, user=current_user).exists()
        if read_later_item_exist:
            read_later_item = get_object_or_404(ReadLater, materi=materi, user=current_user)
            read_later_item.delete()
            response = {"success": True, "read_later_checked": False}
        else:
            ReadLater(materi=materi, user=current_user).save()
            response = {"success": True, "read_later_checked": True}
491
        return response