Example #1
0
 def post(self, request, *args, **kwargs):
     new_message = Messages(
         message=request.POST.get('message'),
         sender=self.request.user,
         reciever_id=self.kwargs.get('reciever_id'),
     )
     new_message.save()
     return self.get(self, request, *args, **kwargs)
Example #2
0
 def create(self, validated_data):
     c = Conversations.objects.get(id=validated_data['conversation_id'])
     m = Messages(conversation_id=c,
                  text=validated_data['text'],
                  date=datetime.now(),
                  sender_id=self.context['user'])
     m.save()
     return m
Example #3
0
 def create(self, validate_data):
     user = Users.objects.get(id=validate_data['sender_id'])
     conversation = Conversations.objects.get(
         id=validate_data['conversation_id'])
     m = Messages(
         sender_id=user,
         conversation_id=conversation,
         text=validate_data['text'],
         date='2019-02-05',
     )
     m.save()
     return m
Example #4
0
    def create(self, validate_data):

        conversation = Conversations.objects.get(
            id=validate_data['conversation_id'])
        m = Messages(
            # sender_id = self.user_profile.user ,
            sender_id=self.contex['user'],
            conversation_id=conversation,
            text=validate_data['text'],
            date=datetime.datetime.now())

        m.save()
        return m
Example #5
0
def conversation_view(request, userparameter):
    if request.method == 'GET':
        pass

    elif request.method == "POST":
        try:
            print(request.POST['message'])
            u = User.objects.filter(first_name="sara")[0]
            c = Conversations.objects.filter(id=int(userparameter))[0]
            Messages(sender_id=u,
                     conversation_id=c,
                     text=request.POST['message'],
                     date=datetime.now()).save()
        except ValueError:
            print("there is no userparameters")

    try:
        messages = Messages.objects.filter(conversation_id=int(userparameter))
    except ValueError:
        messages = []

    return render(request, 'conversationlist.html', {
        "messages": messages,
        "conversations": Conversations.objects.all()
    })
 def fetch_messages(self, data):
     roomName = data["roomName"]
     messages = Messages.last_messages(roomName)
     content = {
         "command": "messages",
         "messages": self.messages_to_json(messages)
     }
     self.send_message(content)
Example #7
0
 def create(self, validated_data):
     # u = Users.objects.get(
     #         token= validated_data['token'])
     print(self.context)
     print('---------------',validated_data)
     c = Conversations.objects.get(
             id=validated_data['conversation_id'])
     m = Messages(
         sender_id=self.context['user'],
         conversation_id=c,
         date=datetime.now(),
         text=validated_data.get('text', None),
         picture=validated_data.get('picture', None),
         file=validated_data.get('file', None)
     )
     m.save()
     return m
Example #8
0
def send_message(request):
    """
    Save message in database. And redirect to chat room. If chat not exists - create new chat room.
    :param request: HttRequest as POST
    :return: If not errors and request POST return redirect to chat room page. Else return error page.
    """
    if request.method == 'POST':
        receiver = User.objects.get(username=request.POST['receiver'])
        sender = User.objects.get(username=request.POST['sender'])
        chats = Chat.objects.filter(users=receiver).filter(users=request.user)
        chat = None
        new_message = Messages()
        if chats.exists():
            # If chat exist get first chat room for current user and receiver
            chat = chats[0]
            old_messages = Messages.objects.filter(chat=chat).filter(new=True)
            set_new_messages_to_old(old_messages)
        else:
            chat = Chat.objects.create()
            chat.users.add(sender, receiver)
        new_message.chat = chat
        new_message.sender = sender
        new_message.text = request.POST['text']
        new_message.new = True
        new_message.save()
        chat.have_new_message = True
        chat.save()
        return redirect('/messages/chat/' + str(chat.id) +'/')
    else:
        return render_to_response('error.html', {'error': REQUEST_TYPE_ERROR}, context_instance=RequestContext(request))
Example #9
0
def send_message_api(request):
    """
    API endpoint for tornado application (chatapp.py). Save message in database and return message object as JSON.
    :param request: HttpRequest from tornado app. Should have chat (chat.id), text (message text),
    sender (sender username) parameters
    :return: Return Message object as JSON.
    """
    if request.method == "POST":
        if request.POST['API_KEY'] == API_KEY:
            chat = Chat.objects.get(id=request.POST['chat'])
            text = request.POST['text']
            sender = User.objects.get(username=request.POST['sender'])
            if sender not in chat.users.all():
                return HttpResponse(json.dumps({'chat': chat.pk, 'Error': 'incorrect chat user'}))
            messages = Messages.objects.filter(chat=chat).filter(new=True)
            set_new_messages_to_old(messages)
            new_message = Messages()
            new_message.sender = sender
            new_message.chat = chat
            new_message.text = text
            new_message.new = True
            new_message.save()
            chat.have_new_message = True
            chat.save()
            return HttpResponse(json.dumps({
                'sender': sender.username,
                'text': text,
                'chat': chat.id,
                'datetime': new_message.datetime.strftime('%d-%m-%Y %H:%M')
            }), content_type="application/json")
def add_message(request):
    if not request.user.is_authenticated:
        return HttpResponseRedirect("/login")
    try:
        data = json.loads(str(request.body, 'utf-8'))
        if request.user.username == data['sender']:
            message = Messages()
            message.sender = User.objects.get(username=data['sender'])
            message.target = User.objects.get(username=data['target'])
            message.timestamp = time()
            message.text = data['text']
            message.date_time = data['date_time']
            message.save()
            return HttpResponse(json.dumps({'errorcode': 0, 'success': True}))
    except Exception:
        return notfound(request)
Example #11
0
def pool_status(request):
    if request.method == 'POST':
        posted_request = request.POST.dict()
        all_keys = list(posted_request.keys())
        usrname = all_keys[len(all_keys) - 1]
        usr = User.objects.get(username=usrname)

        if (request.POST.get('mentors') == 'Select'):
            messages.warning(request, 'Please add a valid mentor!')
            return HttpResponseRedirect('/pool_status')

        if (str(usr.id) == request.POST.get('mentors')):
            messages.warning(
                request, 'Cannot assign the worker as a mentor to himself!')
            return HttpResponseRedirect('/pool_status')

        if (str(usr.profile.worker_pool) == str(request.POST.get('radio')) and
                int(request.POST.get('mentors')) in usr.profile.get_mentors()):
            messages.warning(request, 'Mentor already added!')
            return HttpResponseRedirect('/pool_status')

        current_selected_mentor_id = request.POST.get('mentors')
        current_mentor_user = User.objects.get(id=current_selected_mentor_id)

        if (request.POST.get('radio') == 'A'):
            usr.profile.set_mentors([int(request.POST.get('mentors'))])
        else:
            original_mentors = usr.profile.get_mentors()
            if (usr.profile.worker_pool != request.POST.get('radio')):
                original_mentors = []

            original_mentors.append(int(request.POST.get('mentors')))
            usr.profile.set_mentors(original_mentors)

        current_mentees = current_mentor_user.profile.get_mentees()
        if not (usr.id in current_mentees):
            current_mentees.append(usr.id)
            current_mentor_user.profile.set_mentees(current_mentees)
            current_mentor_user.profile.save()

        tuj_list = TaskUserJunction.objects.filter(worker_id=usr.id)
        for tuj in tuj_list:
            newMessage = Messages(text="Your mentor has been changed",
                                  datetime=datetime.datetime.now(),
                                  sender_id=usr.id,
                                  room_id=tuj.id)
            newMessage.save()
        usr.profile.worker_pool = request.POST.get('radio')
        usr.profile.save()

    user_dict = dict()
    users = User.objects.all()

    mentors = Profile.objects.filter(is_Mentor=True)

    mentors_list = []
    mentor_form = [('Select', 'Select')]

    for mentor in mentors:
        # mentors_list.append(mentor.user.id)
        mentor_form.append((mentor.user.id, mentor.user.username))
    for usr in users:
        if not ('worker' in usr.profile.get_roles()):
            continue
        original_mentor_form = mentor_form.copy()
        if 'mentor' in usr.profile.get_roles():
            mentor_form.remove((usr.id, usr.username))
        form = AssignPools(value=usr.id, mentors=mentor_form)
        current_mentors = []
        for mentor in usr.profile.get_mentors():
            current_mentors.append(User.objects.get(id=mentor))

        user_dict[usr.username] = {
            'form': form,
            'current_mentors': current_mentors
        }
        mentor_form = original_mentor_form.copy()

    return render(request, 'assign_workers_to_pool.html',
                  {'user_dict': user_dict})