Exemple #1
0
def message(request):

    try:
        username = request.META['HTTP_X_USERNAME']
        password = request.META['HTTP_X_PASSWORD']
    except KeyError:
        return HttpResponse(status=401)

    try:
        user = User.objects.get(username=username)
    except User.DoesNotExist:
        return HttpResponse(status=401)

    if not user.check_password(password):
        return HttpResponse(status=401)

    if request.method == 'POST':
        # fetch message body
        body = request.body
        message = json.loads(body)  # deserialize
        chat_message = ChatMessage(
            text=message['text'],
            username=user.username)
        chat_message.save()
        return HttpResponse('')
    else:
        chat_messages = ChatMessage.objects.all()
        text_list = [{'text': x.text, 'username': x.username} for x in chat_messages]
        # serialize
        resp_body = json.dumps(text_list)
        return HttpResponse(resp_body)
Exemple #2
0
def new_message(request):
    ''' функция для создания нового сообщения'''
    if request.user.is_authenticated() and request.method == 'POST':
        companion_id = request.POST["companion_id"]
        author_id = int(request.POST["author_id"])
        message_text = request.POST["message_text"]

        author = request.user

        if author_id == request.user.person_id:
            companion = MyUser.objects.get(person_id=companion_id)
        else:
            companion = MyUser.objects.get(person_id=author_id)
        try:
            #проверяем существует ли беседа между текущими пользователями. Так как в модели chat установлено, что author и companion должны быть уникальными, то если в текущем блоке try не возникает исключения, создаем новую беседу.
            chat = Chat(author=author,
                        companion=companion,
                        user_last_change=request.user)
            chat.save()
            print('new_chat')
        except:
            #если беседа существует, находим её, правильно определив кто является автором, а кто собеседником
            chat = Chat.objects.filter(author=author, companion=companion)
            if not len(chat):
                chat = Chat.objects.filter(companion=author,
                                           author=companion)[0]
            else:
                chat = chat[0]
        message = ChatMessage(chat=chat, user=author, text=message_text)
        message.save()

        return redirect(request.META["HTTP_REFERER"])
    else:
        return HttpResponse('ВЫ не авторизировались.')
Exemple #3
0
def new_message(channel, data):
    simple_text = data.get('text', '')
    comment_regex = r'^\s*{}'.format(CHAT_COMMENT_TAG)
    if not re.match(comment_regex, simple_text):
        user, c = ChatUser.objects.get_or_create(user_id=data['user'])
        m = ChatMessage(data=json.dumps(data), user=user, channel=channel)
        m.save()
Exemple #4
0
    def test_chat_message_basic(self):
        """Tests creation, getters and setter of ChatMessage model"""
        cm = ChatMessage(uuid.uuid4(), "default")
        cm.msg = "Python rulz!"
        cm.user = "******"
        cm.time = time.time()

        self.assertEqual(cm.msg, "Python rulz!")
        self.assertEqual(cm.user, "slok")
 async def send_message(self, text_data):
     user = text_data['payload']['user']
     message = text_data['payload']['message']
     db_message = ChatMessage(user=user, message=message)
     db_message.save()
     # Send message to room group
     await self.channel_layer.group_send(self.room_group_name, {
         'type': 'chat_message',
         'message': message,
         'user': user
     })
    def save_message(self, message_data):
        chunks, chunk_size = len(
            message_data['message']
        ), _model_field_limits['Message__message__max_length']
        message_chunks = [
            message_data['message'][i:i + chunk_size]
            for i in range(0, chunks, chunk_size)
        ]

        first_message_chunk = message_chunks.pop(0)

        with transaction.atomic():
            message = ChatMessage(chat_room_id=self.room_id,
                                  user_id=self.user_id,
                                  datetime=datetime.fromisoformat(
                                      message_data['datetime']),
                                  message=first_message_chunk)

            message.save()
            parent_message_id = message.pk

            for message_chunk in message_chunks:
                message = ChatMessage(chat_room_id=self.room_id,
                                      user_id=self.user_id,
                                      datetime=datetime.fromisoformat(
                                          message_data['datetime']),
                                      message=first_message_chunk,
                                      parent_message_id=parent_message_id)
                message.save()
    def setUp(self):
        """ Create necessary instances before tests """

        self.rental = Rental(address='11 Test Street')
        self.maint_request = MaintRequest(property_ref=self.rental)
        self.chat_message = ChatMessage(maint_request=self.maint_request,
                                        message='A test message')
 async def fetch_messages(self, data):
     # pdb.set_trace()
     messages = ChatMessage.last_20_messages()
     content = {
         'type': 'messages',
         'payload': self.messages_to_json(messages)
     }
     await self.send(json.dumps(content))
Exemple #9
0
 def test_chat_message_save(self):
     """Tests the save of the instance in redis"""
     for i in range(100):
         cm = ChatMessage(uuid.uuid4(), "default")
         cm.msg = "Python rulz!%d" % i
         cm.user = "******" % i
         cm.time = time.time()
         cm.save()
Exemple #10
0
def send_message(request, chatroom_id):

    chatroom = ChatRoom.objects.get(pk=chatroom_id)
    if request.user not in chatroom.users.all():
        data = {
            'message': "You do not have permission to post in this room.",
            'success': False
        }
        return HttpResponse(json.dumps(data), status=401)

    post_data = json.loads(request.body.decode('utf-8'))
    if 'message' not in post_data:
        data = {'message': "No message supplied.", 'success': False}
        return HttpResponse(json.dumps(data), status=400)

    message = ChatMessage(user=request.user,
                          room=chatroom,
                          text=post_data['message'])
    message.save()

    return HttpResponse(json.dumps({'success': True}))
Exemple #11
0
def message_handler(request):
    if request.method == "POST":
        # add new message
        json_data = json.loads(request.body)
        message = json_data.get('message')
        if message:
            msg = ChatMessage(created_by=request.user, message=message)
            msg.save()
            return JsonResponse({'success': True, 'message': 'ok'})

    if request.method == "GET":
        # return messages of public channel limit by 100
        offset = request.GET.get('offset')
        if not offset:
            offset = 0
            raw_sql = "SELECT * FROM chat_chatmessage"
            # "users_user au on  cm.created_by_id = au.id" \
            # "(select last_cleared FROM chat_chatclear where cleared_by_id=" + str(
            #       request.user.id) + ") order by " \
            #              "created_on limit 100 offset " + str(offset) + ";"
            chat_messages = db.get_all_messages(raw_sql)
        return JsonResponse({'success': True, 'data': chat_messages})
Exemple #12
0
def message_handler(request):

    if request.method == "POST":
        #add new message
        json_data = json.loads(request.body)
        message = json_data.get('message')
        if message:
            msg = ChatMessage(created_by=request.user,  message=message)
            msg.save()
            return JsonResponse({'success': True, 'message': 'ok'})

    if request.method == "GET":
        #return messages of public channel limit by 100
        offset = request.GET.get('offset')
        if not offset:
            offset = 0
            raw_sql = "SELECT cm.message, cm.created_on,au.username FROM quickchat.chat_chatmessage cm inner join " \
                      "quickchat.auth_user au on  cm.created_by_id = au.id where created_on > " \
                      "(select last_cleared FROM quickchat.chat_chatclear where cleared_by_id="+str(request.user.id)+") order by " \
                      "created_on limit 100 offset "+str(offset)+";"
            chat_messages = db.get_all_messages(raw_sql)
        return JsonResponse({'success':True, 'data' : chat_messages})
Exemple #13
0
    def test_chat_message_find(self):
        """Tests the find of the instance in redis"""

        uuid_id = uuid.uuid4()
        cm = ChatMessage(uuid_id, "default")
        cm.msg = "Python rulz!"
        cm.user = "******"
        cm.time = time.time()
        cm.save()

        cm_find = ChatMessage.find(uuid_id)

        self.assertEqual(cm_find.msg, cm.msg)
        self.assertEqual(cm_find.user, cm.user)
        self.assertEqual(cm_find.room, cm.room)
Exemple #14
0
    def execute(self):
        expire_date = datetime.now() - timedelta(seconds=settings.CHAT_TIMEOUT)
        appearances = Appearance.objects.filter(timestamp__lte=expire_date)

        for appearance in appearances:
            # generate leave messages in each room
            m = ChatMessage()
            m.room = appearance.room
            m.type = ChatMessage.LEAVE
            m.author = appearance.person
            m.save()

        appearances.delete()
Exemple #15
0
def ajax_say(request):
    room = get_obj_from_request(request.POST, 'room', ChatRoom)
    if room is None:
        return json_failure(design.bad_room_id)

    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'permission_read': room.permission_to_hear(request.user),
            'permission_write': room.permission_to_chat(request.user),
        },
        'success': False,
    }

    if not room.is_active():
        return json_failure(design.room_is_not_active)

    message = request.POST.get('message', '')

    if message == "":
        return json_failure(design.cannot_say_blank_message)

    if len(message) > ChatMessage._meta.get_field('message').max_length: #@UndefinedVariable
        return json_failure(design.message_too_long)

    if not data['user']['permission_write']:
        return json_failure(design.you_lack_write_permission)

    msgType = get_val(request.POST, 'type', ChatMessage.MESSAGE)
    if msgType not in [ChatMessage.MESSAGE, ChatMessage.ACTION]:
        msgType = ChatMessage.MESSAGE

    # we're clear. add the message
    m = ChatMessage()
    m.room = room
    m.type = msgType
    m.author = request.user
    m.message = message
    m.save()

    data['success'] = True
    return json_response(data)
Exemple #16
0
    def execute(self):
        expire_date = datetime.now() - timedelta(seconds=settings.CHAT_TIMEOUT)
        appearances = Appearance.objects.filter(timestamp__lte=expire_date)
        
        for appearance in appearances:
            # generate leave messages in each room
            m = ChatMessage()
            m.room=appearance.room
            m.type=ChatMessage.LEAVE
            m.author=appearance.person
            m.save()

        appearances.delete()
Exemple #17
0
    def test_chat_messages(self):
        """Tests the find of the instance in redis"""

        for i in range(30):
            uuid_id = uuid.uuid4()
            cm = ChatMessage(uuid_id, "room1")
            cm.msg = "Python rulz!%d" % i
            cm.user = "******" % i
            cm.time = time.time()
            cm.save()

        cr = ChatRoom("room1")
        messages = cr.messages(10)
        self.assertEqual(len(messages), 10)

        name_number = 20
        for i in messages:
            self.assertEqual(i.user, "slok%d" % name_number)
            name_number += 1
Exemple #18
0
def save_message(request):
    '''
    Function save message owner in DB,

    Check message out on stop words and replace them.

    Add owner to opponent's contact list.

    If the message is first send notification to tpa side.

    parameters by POST: app_name,owner_id,room_id,message

    [server]/api/save_message

    Example: http://chat.localhost/api/save_message
    '''
    #import pdb; pdb.set_trace()
    b = json.loads(request.body)

    b['message'] = stop_words(b['message'])

    if(check_message(b['message']) == False):
        message = 'This message contains prohibited information!'
    else:
        message = b['message']         
    tpa = Tpa.objects.get(name=b['app_name'])
    owner = ChatUser.objects.get(tpa=tpa,user_id=int(b['owner_id']))
    
    if (owner.gender=='m'):
        balance = get_user_balance(tpa,owner)
        print balance
        if balance < 3:
            return  { 'status': 1, 'message': 'Your account is emply. Please replanish your account.' }
    room = ChatRoom.objects.get(tpa=tpa,id=int(b['room_id']))
    cm = ChatMessage()
    cm.tpa = tpa
    cm.user = owner
    cm.room = room
    cm.message = message
    gender = owner.gender
    cm.save()
    charge_for_chat(cm,room,tpa) #charging
    try:
        arr_participants = []
        for p in b['participants']:
            arr_participants.append(p.split('_')[1])
            mes = { 'action': 'show_message', 'room_id': b['room_id'], 
                    'message': {'id': cm.id, 
                                'created': str(cm.created.time().strftime('%H:%M:%S')),
                                'message':cm.message,
                                'room_id':cm.room_id,
                                'owner': serialize_user(owner)            
                                }
                  }
           
            bclient.publish(p, json.dumps(mes))
            opponent = ChatUser.objects.get(user_id=p.split('_')[1])
            #import pdb; pdb.set_trace()
            if owner != opponent:
                # adding contact
                add_me_to_contact_if_not_exist(tpa,owner,opponent,p)
                contact = _add_contact(tpa.name,owner.user_id,opponent.user_id)
                mes_contact = { 'action': 'update_contact' }
                mes_online = { 'action': 'update_users_online' }
                owner_chanel = '%s_%s' % (b['app_name'], owner.user_id)
                bclient.publish(owner_chanel, json.dumps(mes_contact))
                bclient.publish(owner_chanel, json.dumps(mes_online))
                if room.get_count_messages()<2999:
                    data = {'message': cm.message, 'id': cm.id, 'opponent': serialize_user(owner)}
                    mes = { 'action': 'show_new_message_notification', 'data': data }
                    bclient.publish('%s_%s' % (tpa.name, opponent.user_id), json.dumps(mes))
    except Exception, e:
        print e
Exemple #19
0
def ajax_hear(request):
    """
    get new or all messages
    """
    last_message_str = request.GET.get('last_message', 'null')

    room = get_obj_from_request(request.GET, 'room', ChatRoom)
    if room is None:
        return json_failure(design.bad_room_id)

    # make sure user has permission to be in this room
    data = {
        'user': {
            'is_authenticated': request.user.is_authenticated(),
            'permission_read': room.permission_to_hear(request.user),
            'permission_write': room.permission_to_chat(request.user),
        },
        'room': room.to_dict(),
        'messages': [],
        'success': True
    }

    if request.user.is_authenticated():
        data['user'].update({
            'username': request.user.username,
        })

    if data['user']['permission_read']:
        def add_to_message(msg):
            return {
                'id': msg.id,
                'type': msg.type,
                'author': {
                    'username': msg.author.username,
                    'id': msg.author.id,
                },
                'message': msg.message,
                'timestamp': msg.timestamp,
            }

        if last_message_str == 'null':
            # get entire log for this chat.
            data['messages'] = [add_to_message(x) for x in ChatMessage.objects.filter(room=room)]
        else:
            try:
                last_message_id = int(last_message_str)
            except ValueError:
                last_message_id = 0

            data['messages'] = [add_to_message(x) for x in ChatMessage.objects.filter(room=room, id__gt=last_message_id)]

    if data['user']['permission_write']:
        # mark an appearance in the ChatRoom
        if request.user.is_authenticated() and room.is_active():
            appearances = Appearance.objects.filter(person=request.user, room=room)
            if appearances.count() > 0:
                appearances[0].save() # update the timestamp
            else:
                new_appearance = Appearance()
                new_appearance.room = room
                new_appearance.person = request.user
                new_appearance.save()

                # join message
                m = ChatMessage()
                m.room=room
                m.type=ChatMessage.JOIN
                m.author=request.user
                m.save()

    return json_response(data)
Exemple #20
0
 def save_message(self, message, user):
     """Сохранение нового сообщения в БД."""
     new_message = ChatMessage(user=user, group=self.group, message=message)
     new_message.save()
Exemple #21
0
 def save_message(self, message, user):
     m = ChatMessage(user=user, group=self.group, message=message)
     m.save()
Exemple #22
0
    def test_chat_message_delete(self):
        """Tests the delete of the instance in redis"""

        with self.assertRaises(NotImplementedError):
            cm = ChatMessage(uuid.uuid4(), "default")
            cm.delete()
Exemple #23
0
def log_message_sync(message, m_type, url, language):
    m = ChatMessage(text=message, message_type=m_type, speech_url=url, language=language)
    return m.save()
Exemple #24
0
def show_all_my_chats(request):
    ''' функция для отображения страницы с беседами и обработки ajax-запросов по извлечению сообщений, а также добавлению новых.'''
    if request.user.is_authenticated():
        if request.method == 'GET':
            #определяем все беседы авторизированного пользователя
            my_friends, count_friends = all_friends(request.user)

            new_friends = MyFriends.objects.filter(friend=request.user,
                                                   status=0)

            count_new_friends = MyFriends.objects.filter(friend=request.user,
                                                         status=0).count()

            count_my_photos = UserPhoto.objects.filter(
                user=request.user).count()

            all_chats, count_my_chats = my_chats(request.user)

            return render(
                request, 'my_chats.html', {
                    'person': request.user,
                    'my_friends': my_friends,
                    'new_friends': new_friends,
                    'count_new_friends': count_new_friends,
                    'count_my_friends': count_friends,
                    'person_friends': my_friends,
                    'count_friends': count_friends,
                    'count_my_photos': count_my_photos,
                    'all_chats': all_chats,
                    'count_my_chats': count_my_chats
                })
        #обрабатываем ajax-запросы в различных режимах
        if request.is_ajax():
            mode = request.POST["mode"]

            if mode == '0':
                #определяем все сообщения запрошенной беседы и передаём её в виде строки html-кода

                chat_id = request.POST["chat_id"]
                chat = Chat.objects.get(id=chat_id)
                messages = ChatMessage.objects.filter(chat=chat)

                ajax_response = render_to_string('chat_messages.html', {
                    'message': messages,
                    'user': request.user
                })

                return HttpResponse(ajax_response)

            elif mode == '1':
                #добавляем новое сообщение и извлекаем сообщения из базы со временем размещения больше последнего обновления. Возвращаем новую дату обновления и сообщения в виде строки html-кода.
                text_message = request.POST["message_text"]
                chat_id = request.POST["chat_id"]

                chat = Chat.objects.get(id=chat_id)

                new_message = ChatMessage(chat=chat,
                                          user=request.user,
                                          text=text_message)
                new_message.save()

                chat.user_last_change = request.user
                chat.save()

                old_date = datetime.datetime.strptime(
                    request.POST['last_date'], '%d-%m-%Y %H:%M:%S.%f')

                new_date = chat.last_change
                new_date = new_date.strftime('%d-%m-%Y %H:%M:%S.%f')

                all_new_messages = ChatMessage.objects.filter(
                    chat=chat, date__gt=old_date)

                ajax_response = render_to_string('chat_messages.html', {
                    'message': all_new_messages,
                    'user': request.user
                })

                data = {'new_date': new_date, 'ajax_response': ajax_response}

                return HttpResponse(json.dumps(data),
                                    content_type='application/json')
            elif mode == '2':
                #автоматический опрос на наличие новых записей, отправляется раз в 5 сек со стороны клиента. Возвращаем новую дату обновления и сообщения в виде строки html-кода.
                try:
                    chat_id = request.POST["chat_id"]
                    chat = Chat.objects.get(id=chat_id)

                    old_date = datetime.datetime.strptime(
                        request.POST['last_date'], '%d-%m-%Y %H:%M:%S.%f')

                    new_date = chat.last_change
                    new_date = new_date.strftime('%d-%m-%Y %H:%M:%S.%f')
                    all_new_messages = ChatMessage.objects.filter(
                        chat=chat, date__gt=old_date)

                    ajax_response = render_to_string('chat_messages.html', {
                        'message': all_new_messages,
                        'user': request.user
                    })

                    data = {
                        'new_date': new_date,
                        'ajax_response': ajax_response
                    }
                except Exception as err:
                    print(err)
                return HttpResponse(ajax_response)

    else:
        return HttpResponse("Вы не авторизированы")
Exemple #25
0
def save_message(request):
    '''
    Function save message owner in DB,

    Check if user is available.

    Check message out on stop words and replace them.

    Add owner to opponent's contact list.

    If the message is first send notification to tpa side.

    parameters by POST: app_name,owner_id,room_id,message

    [server]/api/save_message

    Example: http://chat.localhost/api/save_message
    '''
    #import pdb; pdb.set_trace()
    b = json.loads(request.body)
    #time.sleep(2)

    b['message'] = stop_words(b['message'])

    if(check_message(b['message']) == False):
        message = 'This message contains prohibited information!'
    else:
        message = b['message']         
    tpa = Tpa.objects.get(name=b['app_name'])
    owner = ChatUser.objects.get(tpa=tpa,user_id=int(b['owner_id']))
    
    if (owner.gender=='m'):
        balance = get_user_balance(tpa,owner)
        if balance < 3:
            return  { 'status': 1, 'message': 'Your account is emply. Please replanish your account.' }  
        owner.activity = time.time()
        owner.save()

    room = ChatRoom.objects.get(tpa=tpa,id=int(b['room_id']))
    
    # Set servers locale to Kiev time to save same date of message for girl and man
    import pytz, datetime
    local = pytz.utc
    naive = datetime.datetime.strptime (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()), "%Y-%m-%d %H:%M:%S")
    local_dt = local.localize(naive, is_dst=None)
    utc_dt = local_dt.astimezone (pytz.timezone ("Europe/Kiev"))
    
    cm = ChatMessage()
    cm.tpa = tpa
    cm.user = owner
    cm.room = room
    cm.message = message
    cm.created = utc_dt
    gender = owner.gender
    cm.save()
    charge_for_chat(cm,room,tpa) #charging
    
    #try:
    arr_participants = []
    for p in b['participants']:
        arr_participants.append(p.split('_')[1])
        mes = { 'action': 'show_message', 'room_id': b['room_id'], 
                'message': {'id': cm.id, 
                            'created': str(cm.created.time().strftime('%H:%M:%S')),
                            'message':cm.message,
                            'room_id':cm.room_id,
                            'owner': serialize_user(owner),  
                            'participants': b['participants']          
                            }
              }
        print 'send to %s' % p
	opponent = ChatUser.objects.get(user_id=p.split('_')[1])
        if owner != opponent:
            bclient.publish(p, json.dumps(mes))        
        
        #import pdb; pdb.set_trace()
        
        if owner != opponent:
	    
            # check accessebilities
            #import pdb; pdb.set_trace()
            check_avalible_url = get_url_by_name('check_accessebility',{'user_id': opponent.user_id, 'app_name': b['app_name']})
            print 'REQUEST_____%s' % check_avalible_url
            res = json.loads(requests.get(check_avalible_url).content)
            if(res['status']==1):
                print 'noooooo'
                mes = { 'action': 'say_busy', 'message': 'Sorry but I am busy now.', 'user_profile':  serialize_user(opponent)}
                owner_chanel = '%s_%s' % (b['app_name'], owner.user_id)
                bclient.publish(owner_chanel, json.dumps(mes))
            # adding contact 
            is_sent = False
            if opponent.gender == 'w':
                add_me_to_contact_if_not_exist(tpa,owner,opponent,p)
            #if it man just show multiinvite popup
            else:
                
                try:
                    cont = ChatContacts.objects.get(tpa=tpa,owner=opponent,contact=owner)
                except:
                    data = {'message': cm.message, 'opponent': serialize_user(owner), 'id': str(owner.user_id) }
                    mes = { 'action': 'show_multi_invite_notification', 'data': data }
                    bclient.publish('%s_%s' % (b['app_name'], opponent.user_id), json.dumps(mes))
                    is_sent = True                     
            contact = _add_contact(tpa.name,owner.user_id,opponent.user_id)
            mark_new_message(owner,opponent)
            if(opponent.is_online):
                mes_contact = { 'action': 'add_opponent_in_my_contact_list', 'user_id': opponent.user_id, 'profile': serialize_user(opponent) }
                mes_online = { 'action': 'update_users_online' }
                owner_chanel = '%s_%s' % (b['app_name'], owner.user_id)
                opponent_chanel = '%s_%s' % (b['app_name'], opponent.user_id)
                bclient.publish(owner_chanel, json.dumps(mes_contact))
                bclient.publish(owner_chanel, json.dumps(mes_online))
                if is_sent == False:
                    data = {'message': cm.message, 'id': cm.id, 'opponent': serialize_user(owner)}
                    mes = { 'action': 'show_new_message_notification', 'data': data }
                    bclient.publish('%s_%s' % (tpa.name, opponent.user_id), json.dumps(mes))
            # send commant to add this opponent to list of the active opponent in js
            mess_ac = { 'action': 'contact_activate', 'user_id': owner.user_id, 'profile': serialize_user(owner) }
            bclient.publish(opponent_chanel, json.dumps(mess_ac))
            
    #except Exception, e:
    #    print e
    
    

    return  { 'status': 0, 'message': b['message'], 'room_id': str(room.id), 'owner_id': str(owner.id), 'participants': arr_participants }