Fakultas Ilmu Komputer UI

models.py 10.3 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
53
54
55
56
57
58
59
60
61
62
63
    def search(self, search_text):
        search_vector = search.SearchVector("title", weight="A")
        search_query = search.SearchQuery(search_text)

        search_rank = search.SearchRank(search_vector, search_query)

        search_result = (
            self.get_queryset().filter(_search_vector=search_query).annotate(rank=search_rank).order_by("-rank")
        )

        return search_result

64
65
66
class SoftDeletionQuerySet(models.query.QuerySet):
    def delete(self):
        return super(SoftDeletionQuerySet, self).update(deleted_at=timezone.now())
67

68
69
70
71
class SoftDeleteModel(models.Model):
    deleted_at = models.DateTimeField(blank=True, null=True)

    all_objects = MateriManager(alive_only=False)
72
    
73
74
    class Meta:
        abstract = True
75
    
76
77
78
79
80
    def soft_delete(self):
        self.deleted_at = timezone.now()
        self.save()

class Materi(SoftDeleteModel):
igor lestin sianipar's avatar
igor lestin sianipar committed
81
82
    cover = models.ImageField()
    content = models.FileField()
83
84
    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
85
    uploader = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
86
    publisher = models.CharField(max_length=30, default="Penerbit")
87
    release_year = models.IntegerField(default=current_year)
Samuel Dimas Partogi's avatar
Samuel Dimas Partogi committed
88
    pages = models.IntegerField(default=0)
89
    descriptions = models.TextField(default="Deskripsi")    
90
    status = models.CharField(max_length=30, choices=VERIFICATION_STATUS, default=VERIFICATION_STATUS[0][0])
Saul Andre's avatar
Saul Andre committed
91
    categories = models.ManyToManyField(Category)
92
93
    date_created = models.DateTimeField(default=timezone.now)
    date_modified = models.DateTimeField(auto_now=True)
94
    yt_video_id = models.CharField(max_length=100, blank=True, null=True)
95

96
97
98
99
100
101
102
103
104
105
106
    _search_vector = search.SearchVectorField(null=True, editable=False)

    objects = MateriManager()

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

        if "update_fields" not in kwargs or "_search_vector" not in kwargs["update_fields"]:
            self._search_vector = search.SearchVector("title", weight="A")
            self.save(update_fields=["_search_vector"])

107
108
109
110
    @property
    def is_published(self):
        published = False
        if self.verificationreport_set.exists():
111
112
            report = self.verificationreport_set.latest("timestamp")
            published = True if report.status == "Diterima" else False
113
114
115
116
117
118
        return published

    @property
    def published_date(self):
        published_date = None
        if self.verificationreport_set.exists():
119
120
            report = self.verificationreport_set.latest("timestamp")
            if report.status == "Diterima":
121
122
                published_date = report.timestamp
        return published_date
123

124
125
126
127
    @property
    def like_count(self):
        count = Like.objects.filter(materi=self).count()
        return count
128
    
129
130
131
132
    @property
    def comment_count(self):
        count = Comment.objects.filter(materi=self).count()
        return count
133

134
135
136
137
138
    @property
    def review_count(self):
        count = Review.objects.filter(materi=self).count()
        return count

139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    @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)

158
159
160
161
162
    @property
    def is_like(self):
        like = False
        if Like.objects.filter(materi=self).exists():
            like = True
163
        return like
164

165

166
class Comment(models.Model):
167
    username = models.CharField(max_length=100)
168
    profile = models.CharField(max_length=100, default=get_random_color)
169
    comment = models.CharField(max_length=240, default="comments")
170
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True)
171
    user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True)
172
    timestamp = models.DateTimeField(default=timezone.now)
173
174

    def __str__(self):
175
        return self.username
176

177
178
179
180
    @property
    def like_count(self):
        count = LikeComment.objects.filter(comment=self).count()
        return count
181
    
182
183
184
185
186
    @property
    def dislike_count(self):
        count = DislikeComment.objects.filter(comment=self).count()
        return count

187
188
class Review(models.Model):
    username = models.CharField(max_length=100)
189
    profile = models.CharField(max_length=100, default=get_random_color)
190
191
192
193
194
195
196
197
    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

198
199
200
201
202
203
204
205
206
207
208
209

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)

210
211
212
213
214
215

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)

216

217
218
219
220
class ReqMaterial(models.Model):
    title = models.CharField(max_length=100)
    timestamp = models.DateTimeField(default=timezone.now)

insan ramadhan's avatar
insan ramadhan committed
221
222
223
224
225
226
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)

227
228

class ViewStatistics(models.Model):
229
    materi = models.ForeignKey(Materi, models.SET_NULL, null=True, related_name="baca")
230
231
232
233
    timestamp = models.DateTimeField(default=timezone.now)


class DownloadStatistics(models.Model):
234
235
    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")
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    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)
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271


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"]
272
273
274
275
276


class RatingContributor(models.Model):
    timestamp = models.DateTimeField(auto_now=True)
    score = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
277
278
    contributor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='contributor')
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
279
280
281
282
283

    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:
284
            raise ValidationError("Rating score must be integer between 1-5")
285
286
287
    
    class Meta:
        unique_together = ["contributor", "user"]
288

289

290
291
292
293
294
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)
295
    is_rejected = models.BooleanField(default=False)
Anthony Dewa Priyasembada's avatar
Anthony Dewa Priyasembada committed
296
297
298
299
300
301
302
303

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"]