2020-05-01 22:46:15 +08:00
|
|
|
import django.contrib.postgres.fields as postgres
|
|
|
|
from decimal import *
|
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2020-05-05 23:50:48 +08:00
|
|
|
from django.db import models, IntegrityError
|
2020-05-01 22:46:15 +08:00
|
|
|
from django.core.serializers.json import DjangoJSONEncoder
|
2020-05-05 23:50:48 +08:00
|
|
|
from django.db.models import Q
|
2020-05-01 22:46:15 +08:00
|
|
|
from markdownx.models import MarkdownxField
|
|
|
|
from users.models import User
|
2020-10-22 21:45:05 +02:00
|
|
|
from mastodon.api import get_relationships, get_cross_site_id
|
2020-11-22 14:11:59 +01:00
|
|
|
from .utils import clean_url
|
2020-05-01 22:46:15 +08:00
|
|
|
|
|
|
|
|
|
|
|
# abstract base classes
|
|
|
|
###################################
|
2020-11-22 14:11:59 +01:00
|
|
|
class SourceSiteEnum(models.IntegerChoices):
|
|
|
|
DOUBAN = 1, _("豆瓣")
|
|
|
|
|
|
|
|
|
2020-05-01 22:46:15 +08:00
|
|
|
class Resource(models.Model):
|
|
|
|
|
|
|
|
rating_total_score = models.PositiveIntegerField(null=True, blank=True)
|
|
|
|
rating_number = models.PositiveIntegerField(null=True, blank=True)
|
2020-10-22 21:45:05 +02:00
|
|
|
rating = models.DecimalField(
|
|
|
|
null=True, blank=True, max_digits=3, decimal_places=1)
|
2020-05-01 22:46:15 +08:00
|
|
|
created_time = models.DateTimeField(auto_now_add=True)
|
|
|
|
edited_time = models.DateTimeField(auto_now_add=True)
|
2020-10-22 21:45:05 +02:00
|
|
|
last_editor = models.ForeignKey(
|
|
|
|
User, on_delete=models.SET_NULL, related_name='%(class)s_last_editor', null=True, blank=False)
|
2020-05-01 22:46:15 +08:00
|
|
|
brief = models.TextField(blank=True, default="")
|
2020-10-22 21:45:05 +02:00
|
|
|
other_info = postgres.JSONField(
|
|
|
|
blank=True, null=True, encoder=DjangoJSONEncoder, default=dict)
|
2020-11-22 14:11:59 +01:00
|
|
|
# source_url = models.URLField(max_length=500)
|
|
|
|
# source_site = models.SmallIntegerField()
|
2020-05-01 22:46:15 +08:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
constraints = [
|
2020-10-22 21:45:05 +02:00
|
|
|
models.CheckConstraint(check=models.Q(
|
|
|
|
rating__gte=0), name='%(class)s_rating_lowerbound'),
|
|
|
|
models.CheckConstraint(check=models.Q(
|
|
|
|
rating__lte=10), name='%(class)s_rating_upperbound'),
|
|
|
|
]
|
2020-05-01 22:46:15 +08:00
|
|
|
|
|
|
|
def save(self, *args, **kwargs):
|
2020-11-22 14:11:59 +01:00
|
|
|
""" update rating and strip source url scheme & querystring before save to db """
|
2020-05-01 22:46:15 +08:00
|
|
|
if self.rating_number and self.rating_total_score:
|
2020-10-22 21:45:05 +02:00
|
|
|
self.rating = Decimal(
|
|
|
|
str(round(self.rating_total_score / self.rating_number, 1)))
|
2020-05-05 23:50:48 +08:00
|
|
|
elif self.rating_number is None and self.rating_total_score is None:
|
|
|
|
self.rating = None
|
|
|
|
else:
|
|
|
|
raise IntegrityError()
|
2020-11-22 14:11:59 +01:00
|
|
|
# self.source = clean_url(self.source)
|
2020-05-01 22:46:15 +08:00
|
|
|
super().save(*args, **kwargs)
|
|
|
|
|
2020-05-05 23:50:48 +08:00
|
|
|
def calculate_rating(self, old_rating, new_rating):
|
2020-10-22 21:45:05 +02:00
|
|
|
if (not (self.rating and self.rating_total_score and self.rating_number)
|
|
|
|
and (self.rating or self.rating_total_score or self.rating_number))\
|
|
|
|
or (not (self.rating or self.rating_number or self.rating_total_score) and old_rating is not None):
|
2020-05-05 23:50:48 +08:00
|
|
|
raise IntegrityError("Rating integiry error.")
|
|
|
|
if old_rating:
|
|
|
|
if new_rating:
|
|
|
|
# old -> new
|
|
|
|
self.rating_total_score += (new_rating - old_rating)
|
|
|
|
else:
|
|
|
|
# old -> none
|
|
|
|
if self.rating_number >= 2:
|
|
|
|
self.rating_total_score -= old_rating
|
|
|
|
self.rating_number -= 1
|
|
|
|
else:
|
|
|
|
# only one rating record
|
|
|
|
self.rating_number = None
|
|
|
|
self.rating_total_score = None
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
if new_rating:
|
|
|
|
# none -> new
|
|
|
|
if self.rating_number and self.rating_number >= 1:
|
|
|
|
self.rating_total_score += new_rating
|
|
|
|
self.rating_number += 1
|
|
|
|
else:
|
|
|
|
# no rating record before
|
|
|
|
self.rating_number = 1
|
|
|
|
self.rating_total_score = new_rating
|
|
|
|
else:
|
|
|
|
# none -> none
|
|
|
|
pass
|
2020-10-22 21:45:05 +02:00
|
|
|
|
2020-05-05 23:50:48 +08:00
|
|
|
def update_rating(self, old_rating, new_rating):
|
|
|
|
self.calculate_rating(old_rating, new_rating)
|
|
|
|
self.save()
|
|
|
|
|
2020-07-10 21:28:09 +08:00
|
|
|
def get_tags_manager(self):
|
|
|
|
"""
|
|
|
|
Since relation between tag and resource is foreign key, and related name has to be unique,
|
|
|
|
this method works like interface.
|
|
|
|
"""
|
2020-10-04 16:16:50 +02:00
|
|
|
raise NotImplementedError("Subclass should implement this method.")
|
2020-07-10 21:28:09 +08:00
|
|
|
|
2020-09-28 11:21:40 +02:00
|
|
|
def get_marks_manager(self):
|
|
|
|
"""
|
|
|
|
Normally this won't be used.
|
|
|
|
There is no ocassion where visitor can simply view all the marks.
|
|
|
|
"""
|
2020-10-04 16:16:50 +02:00
|
|
|
raise NotImplementedError("Subclass should implement this method.")
|
2020-10-22 21:45:05 +02:00
|
|
|
|
2020-09-28 11:21:40 +02:00
|
|
|
def get_revies_manager(self):
|
|
|
|
"""
|
|
|
|
Normally this won't be used.
|
|
|
|
There is no ocassion where visitor can simply view all the reviews.
|
|
|
|
"""
|
2020-10-04 16:16:50 +02:00
|
|
|
raise NotImplementedError("Subclass should implement this method.")
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_category_mapping_dict(cls):
|
|
|
|
category_mapping_dict = {}
|
|
|
|
for subclass in cls.__subclasses__():
|
|
|
|
category_mapping_dict[subclass.__name__.lower()] = subclass
|
|
|
|
return category_mapping_dict
|
|
|
|
|
|
|
|
@property
|
|
|
|
def category_name(self):
|
|
|
|
return self.__class__.__name__
|
|
|
|
|
|
|
|
@property
|
|
|
|
def verbose_category_name(self):
|
|
|
|
raise NotImplementedError("Subclass should implement this.")
|
|
|
|
|
2020-05-01 22:46:15 +08:00
|
|
|
|
|
|
|
class UserOwnedEntity(models.Model):
|
|
|
|
is_private = models.BooleanField()
|
2020-10-22 21:45:05 +02:00
|
|
|
owner = models.ForeignKey(
|
|
|
|
User, on_delete=models.CASCADE, related_name='user_%(class)ss')
|
2020-05-01 22:46:15 +08:00
|
|
|
created_time = models.DateTimeField(auto_now_add=True)
|
|
|
|
edited_time = models.DateTimeField(auto_now_add=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
|
2020-05-05 23:50:48 +08:00
|
|
|
@classmethod
|
2020-10-22 21:45:05 +02:00
|
|
|
def get_available(cls, resource, request_user, token):
|
|
|
|
# TODO add amount limit for once query
|
2020-05-05 23:50:48 +08:00
|
|
|
"""
|
|
|
|
Returns all avaliable user-owned entities related to given resource.
|
2020-09-28 11:21:40 +02:00
|
|
|
This method handles mute/block relationships and private/public visibilities.
|
2020-05-05 23:50:48 +08:00
|
|
|
"""
|
2020-10-22 21:45:05 +02:00
|
|
|
# the foreign key field that points to resource
|
2020-05-05 23:50:48 +08:00
|
|
|
# has to be named as the lower case name of that resource
|
|
|
|
query_kwargs = {resource.__class__.__name__.lower(): resource}
|
2020-10-22 21:45:05 +02:00
|
|
|
user_owned_entities = cls.objects.filter(
|
|
|
|
**query_kwargs).order_by("-edited_time")
|
|
|
|
|
2020-05-05 23:50:48 +08:00
|
|
|
# every user should only be abled to have one user owned entity for each resource
|
|
|
|
# this is guaranteed by models
|
2020-10-22 21:45:05 +02:00
|
|
|
id_list = []
|
|
|
|
|
2020-10-25 15:47:25 +01:00
|
|
|
# none_index tracks those failed cross site id query
|
|
|
|
none_index = []
|
|
|
|
|
|
|
|
for (i, entity) in enumerate(user_owned_entities):
|
2020-10-22 21:45:05 +02:00
|
|
|
if entity.owner.mastodon_site == request_user.mastodon_site:
|
|
|
|
id_list.append(entity.owner.mastodon_id)
|
|
|
|
else:
|
|
|
|
# TODO there could be many requests therefore make the pulling asynchronized
|
2020-10-25 15:47:25 +01:00
|
|
|
cross_site_id = get_cross_site_id(
|
|
|
|
entity.owner, request_user.mastodon_site, token)
|
|
|
|
if not cross_site_id is None:
|
|
|
|
id_list.append(cross_site_id)
|
|
|
|
else:
|
|
|
|
none_index.append(i)
|
|
|
|
# populate those query-failed None postions
|
|
|
|
# to ensure the consistency of the orders of
|
|
|
|
# the three(id_list, user_owned_entities, relationships)
|
|
|
|
id_list.append(request_user.mastodon_id)
|
2020-10-22 21:45:05 +02:00
|
|
|
|
2020-05-05 23:50:48 +08:00
|
|
|
# Mastodon request
|
2020-10-22 21:45:05 +02:00
|
|
|
relationships = get_relationships(
|
|
|
|
request_user.mastodon_site, id_list, token)
|
|
|
|
mute_block_blocked_index = []
|
|
|
|
following_index = []
|
|
|
|
for i, r in enumerate(relationships):
|
|
|
|
# the order of relationships is corresponding to the id_list,
|
|
|
|
# and the order of id_list is the same as user_owned_entiies
|
2020-05-06 00:16:27 +08:00
|
|
|
if r['blocking'] or r['blocked_by'] or r['muting']:
|
2020-10-22 21:45:05 +02:00
|
|
|
mute_block_blocked_index.append(i)
|
2020-05-06 00:16:27 +08:00
|
|
|
if r['following']:
|
2020-10-22 21:45:05 +02:00
|
|
|
following_index.append(i)
|
|
|
|
available_entities = [
|
|
|
|
e for i, e in enumerate(user_owned_entities)
|
|
|
|
if ((e.is_private == True and i in following_index) or e.is_private == False or e.owner == request_user)
|
2020-10-25 15:47:25 +01:00
|
|
|
and not i in mute_block_blocked_index and not i in none_index
|
2020-10-22 21:45:05 +02:00
|
|
|
]
|
|
|
|
return available_entities
|
2020-05-05 23:50:48 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get_available_user_data(cls, owner, is_following):
|
|
|
|
"""
|
|
|
|
Returns all avaliable owner's entities.
|
|
|
|
|
|
|
|
:param owner: visited user
|
|
|
|
:param is_following: if the current user is following the owner
|
|
|
|
"""
|
|
|
|
user_owned_entities = cls.objects.filter(owner=owner)
|
|
|
|
if not is_following:
|
|
|
|
user_owned_entities = user_owned_entities.exclude(is_private=True)
|
|
|
|
return user_owned_entities
|
|
|
|
|
2020-05-01 22:46:15 +08:00
|
|
|
|
|
|
|
# commonly used entity classes
|
|
|
|
###################################
|
|
|
|
class MarkStatusEnum(models.IntegerChoices):
|
2020-05-05 23:50:48 +08:00
|
|
|
WISH = 1, _('Wish')
|
|
|
|
DO = 2, _('Do')
|
2020-05-01 22:46:15 +08:00
|
|
|
COLLECT = 3, _('Collect')
|
|
|
|
|
|
|
|
|
|
|
|
class Mark(UserOwnedEntity):
|
|
|
|
status = models.SmallIntegerField(choices=MarkStatusEnum.choices)
|
|
|
|
rating = models.PositiveSmallIntegerField(blank=True, null=True)
|
2020-05-05 23:50:48 +08:00
|
|
|
text = models.CharField(max_length=500, blank=True, default='')
|
2020-05-01 22:46:15 +08:00
|
|
|
|
2020-07-10 21:28:09 +08:00
|
|
|
def __str__(self):
|
|
|
|
return f"({self.id}) {self.owner} {self.status}"
|
|
|
|
|
2020-05-01 22:46:15 +08:00
|
|
|
class Meta:
|
|
|
|
abstract = True
|
|
|
|
constraints = [
|
2020-10-22 21:45:05 +02:00
|
|
|
models.CheckConstraint(check=models.Q(
|
|
|
|
rating__gte=0), name='mark_rating_lowerbound'),
|
|
|
|
models.CheckConstraint(check=models.Q(
|
|
|
|
rating__lte=10), name='mark_rating_upperbound'),
|
2020-05-01 22:46:15 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
class Review(UserOwnedEntity):
|
|
|
|
title = models.CharField(max_length=120)
|
|
|
|
content = MarkdownxField()
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.title
|
|
|
|
|
|
|
|
class Meta:
|
2020-05-05 23:50:48 +08:00
|
|
|
abstract = True
|
2020-07-10 21:28:09 +08:00
|
|
|
|
|
|
|
|
|
|
|
class Tag(models.Model):
|
|
|
|
content = models.CharField(max_length=50)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.content
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|