Fakultas Ilmu Komputer UI

models.py 11.2 KB
Newer Older
Saul Andre's avatar
Saul Andre committed
1
import random
2
import datetime
3
import math
4

5
from django.contrib.postgres import search
6
from django.core.exceptions import ValidationError
7
from django.core.validators import MinValueValidator, MaxValueValidator
8
from django.db import models
9
from django.utils import timezone
10

igor lestin sianipar's avatar
igor lestin sianipar committed
11
12
13
from authentication.models import User

VERIFICATION_STATUS = [
14
15
    ("PENDING", "Diproses"),
    ("APPROVE", "Diterima"),
16
    ("DISAPPROVE", "Ditolak"),
17
    ("REVISION", "Perbaikan"),
18
    ("BLOCKED", "Diblokir"),
igor lestin sianipar's avatar
igor lestin sianipar committed
19
]
Samuel Dimas's avatar
Samuel Dimas committed
20

21

Samuel Dimas's avatar
Samuel Dimas committed
22
# Create your models here.
23
24


25
def get_random_color():
Saul Andre's avatar
Saul Andre committed
26
    color = "%06x" % random.randint(0, 0xFFFFFF)
27
28
    return color

29
30
def current_year():
    return datetime.date.today().year
Saul Andre's avatar
Saul Andre committed
31
32
33

class Category(models.Model):
    name = models.CharField(max_length=20)
34
35
    description = models.TextField(blank=False, default="")
    archived = models.BooleanField(default=False, blank=False)
36
    archived_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Saul Andre's avatar
Saul Andre committed
37
38
39
40

    def __str__(self):
        return self.name

41

42
class MateriManager(models.Manager):
43
44
45
46
47
48
49
50
    def __init__(self, *args, **kwargs):
        self.alive_only = kwargs.pop('alive_only', True)
        super(MateriManager, self).__init__(*args, **kwargs)

    def get_queryset(self):
        if self.alive_only:
            return SoftDeletionQuerySet(self.model).filter(deleted_at=None)
        return SoftDeletionQuerySet(self.model)
51
        
52
    def search(self, search_text):
53
54
55
56
57
58
59
        search_vector = None
        for field, weight in Materi.SEARCH_INDEX:
            if search_vector is None:
                search_vector = search.SearchVector(field, weight=weight)
            else:
                search_vector += search.SearchVector(field, weight=weight)

60
61
62
63
64
        search_query = search.SearchQuery(search_text)

        search_rank = search.SearchRank(search_vector, search_query)

        search_result = (
65
66
67
68
            self.get_queryset()
            .filter(_search_vector=search_query)
            .annotate(rank=search_rank)
            .order_by("-rank")
69
70
71
72
        )

        return search_result

73

74
75
76
class SoftDeletionQuerySet(models.query.QuerySet):
    def delete(self):
        return super(SoftDeletionQuerySet, self).update(deleted_at=timezone.now())
77

78
79
80
81
class SoftDeleteModel(models.Model):
    deleted_at = models.DateTimeField(blank=True, null=True)

    all_objects = MateriManager(alive_only=False)
82
    
83
84
    class Meta:
        abstract = True
85
    
86
87
88
89
90
    def soft_delete(self):
        self.deleted_at = timezone.now()
        self.save()

class Materi(SoftDeleteModel):
igor lestin sianipar's avatar
igor lestin sianipar committed
91
92
    cover = models.ImageField()
    content = models.FileField()
93
94
    title = models.CharField(max_length=50, default="Judul")
    author = models.CharField(max_length=30, default="Penyusun")
igor lestin sianipar's avatar
igor lestin sianipar committed
95
    uploader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
96
    publisher = models.CharField(max_length=30, default="Penerbit")
97
    release_year = models.IntegerField(default=current_year)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
98
    pages = models.IntegerField(default=0)
99
    descriptions = models.TextField(default="Deskripsi")    
100
    status = models.CharField(max_length=30, choices=VERIFICATION_STATUS, default=VERIFICATION_STATUS[0][0])
Saul Andre's avatar
Saul Andre committed
101
    categories = models.ManyToManyField(Category)
102
103
    date_created = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(auto_now=True)
104
    yt_video_id = models.CharField(max_length=100, blank=True, null=True)
105

106
107
    _search_vector = search.SearchVectorField(null=True, editable=False)

108
109
110
111
112
113
114
115
    SEARCH_INDEX = (
        ("title", "A"),
        ("author", "A"),
        ("publisher", "C"),
        ("descriptions", "C"),
        ("uploader", "D"),
    )

116
117
118
119
    objects = MateriManager()

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
120
121
122
123
124
125
126
127
128
129
130
131
132
        search_index = {field: weight for (field, weight) in Materi.SEARCH_INDEX}
        if "update_fields" in kwargs:
            is_search_index_updated = bool(
                set(search_index.keys()) & set(kwargs["update_fields"])
            )

        if ("update_fields" not in kwargs) or (is_search_index_updated):
            self._search_vector = None
            for field, weight in search_index.items():
                if self._search_vector is None:
                    self._search_vector = search.SearchVector(field, weight=weight)
                else:
                    self._search_vector += search.SearchVector(field, weight=weight)
133
134
135

            self.save(update_fields=["_search_vector"])

136
137
138
139
    @property
    def is_published(self):
        published = False
        if self.verificationreport_set.exists():
140
141
            report = self.verificationreport_set.latest("timestamp")
            published = True if report.status == "Diterima" else False
142
143
144
145
146
147
        return published

    @property
    def published_date(self):
        published_date = None
        if self.verificationreport_set.exists():
148
149
            report = self.verificationreport_set.latest("timestamp")
            if report.status == "Diterima":
150
151
                published_date = report.timestamp
        return published_date
152

153
154
155
156
    @property
    def like_count(self):
        count = Like.objects.filter(materi=self).count()
        return count
157
    
158
159
160
161
    @property
    def comment_count(self):
        count = Comment.objects.filter(materi=self).count()
        return count
162

163
164
165
166
167
    @property
    def review_count(self):
        count = Review.objects.filter(materi=self).count()
        return count

168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    @staticmethod
    def earliest_materi_timestamp():
        return Materi.objects.earliest('date_created').date_created.timestamp()

    @property
    def seconds_since_earliest_materi(self):
        return self.date_created.timestamp() - Materi.earliest_materi_timestamp()

    @property
    def view_count(self):
        count = ViewStatistics.objects.filter(materi=self).count()
        return count

    @property
    def hot_score(self):
        view_score = math.log(max(self.view_count, 1), 10)
        time_score = self.seconds_since_earliest_materi / 604800 # 1 week
        return round(view_score + time_score, 7)

187
188
189
190
191
    @property
    def is_like(self):
        like = False
        if Like.objects.filter(materi=self).exists():
            like = True
192
        return like
193

194

195
class Comment(models.Model):
196
    username = models.CharField(max_length=100)
197
    profile = models.CharField(max_length=100, default=get_random_color)
198
    comment = models.CharField(max_length=240, default="comments")
199
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
200
    user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
201
    timestamp = models.DateTimeField(default=timezone.now)
202
203

    def __str__(self):
204
        return self.username
205

206
207
208
209
    @property
    def like_count(self):
        count = LikeComment.objects.filter(comment=self).count()
        return count
210
    
211
212
213
214
215
    @property
    def dislike_count(self):
        count = DislikeComment.objects.filter(comment=self).count()
        return count

216
217
class Review(models.Model):
    username = models.CharField(max_length=100)
218
    profile = models.CharField(max_length=100, default=get_random_color)
219
220
221
222
223
224
225
226
    review = models.TextField(default="review")
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
    timestamp = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.username

227
228
229
230
231
232
233
234
235
236
237
238

class LikeComment(models.Model):
    comment = models.ForeignKey(Comment, models.SET_NULL, null=True)
    timestamp = models.DateTimeField(default=timezone.now)
    session_id = models.CharField(max_length=32, blank=False)


class DislikeComment(models.Model):
    comment = models.ForeignKey(Comment, models.SET_NULL, null=True)
    timestamp = models.DateTimeField(default=timezone.now)
    session_id = models.CharField(max_length=32, blank=False)

239
240
241
242
243
244

class Like(models.Model):
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
    timestamp = models.DateTimeField(default=timezone.now)
    session_id = models.CharField(max_length=32, blank=False)

245

246
247
248
249
class ReqMaterial(models.Model):
    title = models.CharField(max_length=100)
    timestamp = models.DateTimeField(default=timezone.now)

insan ramadhan's avatar
insan ramadhan committed
250
251
252
253
254
255
class SubmitVisitor(models.Model):
    user_id = models.CharField(max_length=50)
    email = models.CharField(max_length=50)
    msg = models.CharField(max_length=100)
    timestamp = models.DateTimeField(default=timezone.now)

256
257

class ViewStatistics(models.Model):
258
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True, related_name="baca")
259
260
261
262
    timestamp = models.DateTimeField(default=timezone.now)


class DownloadStatistics(models.Model):
263
264
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True, related_name="unduh")
    downloader = models.ForeignKey(User, models.SET_NULL, blank=True, null=True, related_name="riwayat_unduh")
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    timestamp = models.DateTimeField(default=timezone.now)


class DummyLike(models.Model):
    item = models.ForeignKey(Like, on_delete=models.CASCADE)


class DummyViewStatistics(models.Model):
    item = models.ForeignKey(ViewStatistics, on_delete=models.CASCADE)


class DummyDownloadStatistics(models.Model):
    item = models.ForeignKey(DownloadStatistics, on_delete=models.CASCADE)


class DummyComment(models.Model):
    item = models.ForeignKey(Comment, on_delete=models.CASCADE)
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300


class Rating(models.Model):
    materi = models.ForeignKey(Materi, models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    timestamp = models.DateTimeField(default=timezone.now)
    score = models.IntegerField()

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if 1 <= self.score <= 5:
            super().save(force_insert, force_update, using, update_fields)
        else:
            raise ValidationError("Rating score must be integer between 1-5")

    def __str__(self):
        return "Material:{} | User:{} | Rating:{}".format(self.materi.title, self.user.name, self.score)

    class Meta:
        unique_together = ["materi", "user"]
301
302
303
304
305


class RatingContributor(models.Model):
    timestamp = models.DateTimeField(auto_now=True)
    score = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
306
307
    contributor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='contributor')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
308
309
310
311
312

    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if 1 <= self.score <= 5:
            super().save(force_insert, force_update, using, update_fields)
        else:
313
            raise ValidationError("Rating score must be integer between 1-5")
314
315
316
    
    class Meta:
        unique_together = ["contributor", "user"]
317

318

319
320
321
322
323
class LaporanMateri(models.Model):
    materi = models.ForeignKey(Materi, on_delete=models.CASCADE, max_length=120)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    laporan = models.TextField(validators=[MinValueValidator(30), MaxValueValidator(120)], default="")
    timestamp = models.DateTimeField(default=timezone.now)
324
    is_rejected = models.BooleanField(default=False)
Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
325
326
327
328
329
330
331
332

class ReadLater(models.Model):
    materi = models.ForeignKey(Materi, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(default=timezone.now)

    class Meta:
        unique_together = ["materi", "user"]