Completed
Push — master ( 275057...223d4e )
by
unknown
10s
created

MessageSerializer.validate()   C

Complexity

Conditions 9

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 6.4615
cc 9
1
# -*- coding: utf-8 -*-
2
from rest_framework import serializers
3
4
from sigma_chat.models.chat import Chat
5
from sigma_chat.models.message import Message
6
from sigma_core.models.user import User
7
from rest_framework.serializers import ValidationError
8
9
import requests
10
import json
11
12
class MessageSerializer(serializers.ModelSerializer):
13
    """
14
    Serialize Message model.
15
    """
16
    class Meta:
17
        model = Message
18
19
    def validate(self, data):
20
        if "chatmember_id" not in data:
21
            raise ValidationError("No user given.")
22
        if "chat_id" not in data:
23
            raise ValidationError("No chat given.")
24
        if data['chat_id'].id != data['chatmember_id'].chat.id:
25
            raise ValidationError("ChatMember not allowed to publish on this chat.")
26
        if (not "text" in data or data['text'] is None or data['text'] == "") and (not 'attachment' in data or data['attachment'] is None):
27
            raise ValidationError("You must send either a text or a file.")
28
29
        return data
30
31
    ################################################################
32
    # CHAT                                                         #
33
    ################################################################
34
35
    def save(self, *args, **kwargs):
36
        super(MessageSerializer, self).save(*args, **kwargs)
37
        """
38
        NO_PROXY = {
39
            'no': 'pass',
40
        }
41
        message = {'message': json.dumps({
42
                    'chat':{'id': self.data['chat_id']},
43
                    'chatmember':{'id': self.data['chatmember_id']},
44
                    'text': self.data['text'],
45
                    'attachment': self.data['attachment'],
46
                    'date': self.data['date']
47
                })
48
            }
49
        requests.post('http://localhost:8000/tornado/chat/?secret_key=', data=message, proxies=NO_PROXY)
50
        """
51