myModelSerializer.py 5.68 KB
Newer Older
1
from rest_framework import serializers
Florent Chehab's avatar
Florent Chehab committed
2
from rest_framework.validators import ValidationError
3
from django.utils import timezone
4
from .pendingModeration import PendingModeration
5
from django.contrib.contenttypes.models import ContentType
Florent Chehab's avatar
Florent Chehab committed
6
from .myModel import MyModel
Florent Chehab's avatar
Florent Chehab committed
7
from .pendingModeration import PendingModerationSerializer
Florent Chehab's avatar
Florent Chehab committed
8
from backend.utils import get_user_level
9
from backend.permissions import is_moderation_required
10

Florent Chehab's avatar
Florent Chehab committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
CLEANED_MY_MODEL_DATA = {
    'moderated_by': None,
    'moderated_on': None,
    'updated_by': None,
    'updated_on': None,
}


def override_data(old_data, new_data):
    for key in new_data:
        old_data[key] = new_data[key]
    return old_data


25
26
27
28
29
class MyModelSerializer(serializers.ModelSerializer):
    moderated_on = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_on = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", read_only=True)
30
31
    moderated_by = serializers.CharField(read_only=True)
    updated_by = serializers.CharField(read_only=True)
32
    pending_moderation = serializers.SerializerMethodField()
Florent Chehab's avatar
Florent Chehab committed
33
    model_config = serializers.SerializerMethodField()
34

Florent Chehab's avatar
Florent Chehab committed
35
36
    def get_model_config(self, obj):
        return self.Meta.model.model_config
37

38
39
40
41
42
    def get_pending_moderation(self, obj):
        if self.context['view'].action != 'list':
            return PendingModerationSerializer(obj.pending_moderation, many=True, read_only=True, context=self.context).data
        return None

43
44
45
    class Meta:
        model = MyModel

Florent Chehab's avatar
Florent Chehab committed
46
47
48
49
50
51
52
53
54
    def my_validate(self, attrs):
        return attrs

    def validate(self, attrs):
        self.user = self.get_user_in_request()
        self.user_level = get_user_level(self.user)

        if "obj_moderation_level" in attrs:
            requested_obj_moder_lv = attrs["obj_moderation_level"]
55

Florent Chehab's avatar
Florent Chehab committed
56
57
58
59
60
61
            if requested_obj_moder_lv > self.user_level:
                raise ValidationError(
                    "You can't request moderation for a higher rank than you.")

        return self.my_validate(attrs)

62
63
64
    def get_user_in_request(self):
        return self.context['request'].user

65
    def set_model_attr_no_moder(self, moderated_and_updated):
66
        user = self.get_user_in_request()
67
        now = timezone.now()
Florent Chehab's avatar
Florent Chehab committed
68
69
70
71
        self.override_validated_data({
            'moderated_by': user,
            'moderated_on': now,
        })
72
73

        if moderated_and_updated:
Florent Chehab's avatar
Florent Chehab committed
74
75
76
77
            self.override_validated_data({
                'updated_by': user,
                'updated_on': now,
            })
78
79

    def clean_validated_data(self):
Florent Chehab's avatar
Florent Chehab committed
80
        self.override_validated_data(CLEANED_MY_MODEL_DATA)
81

82
83
84
85
86
    def get_pending_models(self):
        ct = ContentType.objects.get_for_model(self.Meta.model)
        return PendingModeration.objects.filter(
            content_type=ct, object_id=self.instance.pk)

Florent Chehab's avatar
Florent Chehab committed
87
88
89
90
91
92
93
94
95
96
    def override_validated_data(self, new_data):
        """
        Method used to force specific attributes when saving a model
        """
        for key in new_data:
            self.validated_data[key] = new_data[key]

    def my_pre_save(self):
        pass

Florent Chehab's avatar
Florent Chehab committed
97
98
    def save(self, *args, **kwargs):
        return self.my_save(*args, **kwargs)
99

Florent Chehab's avatar
Florent Chehab committed
100
    def my_save(self, *args, **kwargs):
101
        user = self.get_user_in_request()
102
        self.clean_validated_data()
Florent Chehab's avatar
Florent Chehab committed
103
        self.my_pre_save()
104

105
106
        model_moderation_level = self.Meta.model.model_config['moderation_level']
        if is_moderation_required(model_moderation_level, self.instance, self.user, self.user_level):
107
108
            if self.instance is None:  # we need to create the main model
                self.instance = super(
Florent Chehab's avatar
Florent Chehab committed
109
                    MyModelSerializer, self).save(*args, **kwargs)
110

111
            objs_pending_db = self.get_pending_models()
112

Florent Chehab's avatar
Florent Chehab committed
113
114
115
116
117
118
119
120
121
            data_to_save = dict()
            for key in self.validated_data:
                try:
                    # retreive the submitted data
                    data_to_save[key] = self.initial_data[key]
                except KeyError:
                    pass

            data_to_save = override_data(data_to_save, CLEANED_MY_MODEL_DATA)
122
123
            if len(objs_pending_db) > 0:
                pending_instance = objs_pending_db[0]
124
125
                pending_instance.updated_on = timezone.now()
                pending_instance.updated_by = user
Florent Chehab's avatar
Florent Chehab committed
126
                pending_instance.new_object = data_to_save
127
            else:
Florent Chehab's avatar
Florent Chehab committed
128
                # there is no pending instance, we have to create one
129
130
                pending_instance = PendingModeration(
                    referenced_object=self.instance,
131
132
                    updated_by=user,
                    updated_on=timezone.now(),
Florent Chehab's avatar
Florent Chehab committed
133
                    new_object=data_to_save
134
                )
Florent Chehab's avatar
Florent Chehab committed
135

136
            pending_instance.save()
137
138
139
            return self.instance

        else:
140

141
            moderated_and_updated = True
142
            if self.instance is None:
143
                self.set_model_attr_no_moder(moderated_and_updated)
Florent Chehab's avatar
Florent Chehab committed
144
                return super(MyModelSerializer, self).save(*args, **kwargs)
145
146
            else:
                # We check if we don't have any moderation pending
147
                objs_pending_db = self.get_pending_models()
148
                if len(objs_pending_db) > 0:
149
150
151
152
153
154
155
                    obj_pending_db = objs_pending_db[0]
                    self.clean_validated_data()  # Make that it is done...
                    if obj_pending_db.new_object == self.validated_data:
                        moderated_and_updated = False
                        self.validated_data['updated_by'] = obj_pending_db.updated_by
                        self.validated_data['updated_on'] = obj_pending_db.updated_on

156
157
                    objs_pending_db.delete()

158
                self.set_model_attr_no_moder(moderated_and_updated)
Florent Chehab's avatar
Florent Chehab committed
159
                return super(MyModelSerializer, self).save(*args, **kwargs)