Esempio n. 1
0
    def reply_to_chat(chat_id, body):
        body = body.strip()
        if len(body) == 0:
            return False

        in_reply_to_chat = Chat.objects.get(id=chat_id)
        member = in_reply_to_chat.owner
        try:
            Chat(sender='Opencircles',
                 recipient='SELF',
                 body=body,
                 owner=member,
                 time_chat_sent=datetime.datetime.now(),
                 has_been_responded_to=True).save()
            in_reply_to_chat.has_been_responded_to = True
            in_reply_to_chat.save()

            instance = fcm_utils.Fcm()
            registration_id = member.device_token

            fcm_data = {
                'request_type': 'REPLY_TO_CHAT',
                'sender': 'Opencircles',
                'body': body,
                'time_sent':
                datetime.datetime.now().strftime('%Y-%m-%d %H-%m-%s')
            }
            instance.data_push("single", registration_id, fcm_data)
            return True
        except Exception as exp:
            print(exp)
            return False
Esempio n. 2
0
    def send_single_chat(message, member, message_channel):
        try:
            if message_channel == 1:
                Chat(sender='Opencircles',
                     recipient='SELF',
                     body=message,
                     owner=member,
                     time_chat_sent=datetime.datetime.now(),
                     has_been_responded_to=True).save()
                instance = fcm_utils.Fcm()
                registration_id = member.device_token

                fcm_data = {
                    'request_type':
                    'REPLY_TO_CHAT',
                    'sender':
                    'Opencircles',
                    'body':
                    message,
                    'time_sent':
                    datetime.datetime.now().strftime('%Y-%m-%d %H-%m-%s')
                }
                instance.data_push("single", registration_id, fcm_data)
                return True
            else:
                print(member.phone_number)
                print(message)
                response = sms_utils.Sms().sendsms(member.phone_number,
                                                   message)
                return response
        except Exception as exp:
            print(exp)
            return False
Esempio n. 3
0
    def send_chat_to_all_members(message, message_channel):
        if message_channel == 1:
            instance = fcm_utils.Fcm()
            device_tokens = Member.objects.all().values_list('device_token',
                                                             flat=True)

            fcm_data = {
                'request_type': 'REPLY_TO_CHAT',
                'sender': 'Opencircles',
                'body': message,
                'time_sent':
                datetime.datetime.now().strftime('%Y-%m-%d %H-%m-%s')
            }

            members = Member.objects.all()
            for obj in members:
                Chat(sender='Opencircles',
                     recipient='SELF',
                     body=message,
                     owner=obj,
                     time_chat_sent=datetime.datetime.now(),
                     has_been_responded_to=True).save()
            try:
                instance.data_push("multiple", device_tokens, fcm_data)
                return True
            except:
                return False
        else:
            member_phone_numbers = Member.objects.all().values_list(
                'phone_number', flat=True)
            phone_numbers = ','.join(member_phone_numbers)
            print(phone_numbers)
            response, unsent = sms_utils.Sms().sendmultiplesms(
                phone_numbers, message)
            return response
Esempio n. 4
0
    def receive(self, text_data):
        """
       Recebe a mensagem do websocket e envia para o grupo.
        """
        text_data_json = json.loads(text_data)
        username = text_data_json['username']
        message = text_data_json['message']

        # armazena a mensagem.
        empresa = User.objects.get(
            username=self.group_name.replace('chat_', '').replace(
                self.scope['user'].username, '').replace('-', ''))
        Chat(cliente=self.scope['user'],
             empresa=empresa,
             msg=message,
             enviado=True).save()

        client = User.objects.filter(username=self.scope['user'])
        empres = User.objects.filter(username=empresa)

        t1 = Chat.objects.filter(cliente=client[0]).filter(empresa=empres[0])

        print(t1)

        async_to_sync(self.channel_layer.group_send)(self.group_name, {
            'type': 'chat_message',
            'username': username,
            'message': message,
        })
Esempio n. 5
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('ВЫ не авторизировались.')
Esempio n. 6
0
def post(request):
    global aiml_handle, response_queue, cant_answer_count
    if request.method == "POST":
        msg = request.POST.get('msgbox', None)
        print('Our value = ', msg)

        chat_message = Chat(user=request.user, message=msg, human_bot=True)
        if msg != '':
            chat_message.save()

        response = aiml_handle.respond(preprocess_data(msg))
        if response == '':
            response_queue = response_queue + " " + msg
            cant_answer_count = cant_answer_count + 1
            found = 0
            if cant_answer_count > 2:
                lsa_Keywords = lsa_fetch(response_queue)
                #print lsa_Keywords
                for keyword_Lsa in lsa_Keywords:
                    response = aiml_handle.respond(
                        preprocess_data("Lsa "+keyword_Lsa))
                    print ("Lsa = " + response)
                    if(response != ''):
                        found = 1
                        response_queue = ""
                        cant_answer_count = 0
                        break
            if found == 0:
                result = ":( Sorry , response Not Found Can you Elaborate !!!"

        if(response != ''):
            response_queue = ""
            cant_answer_count = 0
            result = response
            if response[0] == '@':
                result_list = database_fetch(response[1:])
                result = json_html(result_list)
            elif response[0] == '$':
                result = chart_display(response[1:])

        chat_message2 = Chat(
            user=request.user, message=result, human_bot=False)
        chat_message2.save()

        return JsonResponse({'msg': msg, 'user': chat_message.user.username})
    else:
        return HttpResponse('Request must be POST.')
def message_save(request):
    if request.method == 'POST':
        msg = request.POST.get('msgValue', None)
        user_id = request.POST.get('user_id', None)
        user = get_user_model().objects.get(id=user_id)
        chat = Chat(user=user, message=msg)
        if msg or msg != '':
            chat.save()
        return JsonResponse({'msg': msg, 'user': chat.user.username})
Esempio n. 8
0
 def create(self, validated_data):
     users = validated_data.pop("users")
     data = validated_data.pop("datatext")
     chat = Chat(data=data)
     chat.save()
     for user in users:
         informer = get_profile(user)
         chat.participants.add(informer)
     return chat
Esempio n. 9
0
 def create(self, validated_data):
     participants = validated_data.get('participants')
     participants = self.check_participant_blacklist(participants)
     chat = Chat()
     if not validated_data.get('is_chat'):
         chat.is_chat = True
         chat.creator = self.context['request'].user
     chat.save()
     return chat
Esempio n. 10
0
 def create(self, validated_data):
     participants = validated_data.pop("participants")
     chat = Chat()
     chat.save()
     for username in participants:
         contact = get_user_contact(username)
         chat.participants.add(contact)
     chat.save()
     return chat
Esempio n. 11
0
def post(request):
    if request.method == "POST":
        msg = request.POST.get('msgbox', None)
        print('Our value = ', msg)
        chat_message = Chat(user=request.user, message=msg)
        if msg != '':
            chat_message.save()
        return JsonResponse({'msg': msg, 'user': chat_message.user.username})
    else:
        return HttpResponse('Request must be POST.')
def chat_send(request):
    if request.method == "POST":
        uploadForm = UploadFileForm
        chatForm = ChatForm

        current_user = request.user
        user = current_user.username
        form = ChatForm(request.POST)
        if form.is_valid:
            message = request.POST.get('message')
            quote_ref = request.POST.get('quote_ref')
            file_name = request.POST.get('file_name')

            #ckeck if user is freelancer (used in the chat to align messages to left or right)
            if request.user.is_superuser:
                superuser = True
                quote = Quote.objects.get(id=quote_ref)
                user = quote.submitted_by
            else:
                superuser = False
                user = user

            #create the chat object
            chat_instance = Chat(message=message,
                                 quote_ref=quote_ref,
                                 file_name=file_name,
                                 user=user,
                                 superuser=superuser)
            chat_instance.save()

        #if the chat message is send by the customer, change the file status to pending
        if not request.user.is_superuser:
            quote_file = QuoteFiles.objects.get(quote_ref=quote_ref,
                                                file_name=file_name)
            quote_file.status = "Pending"
            quote_file.save()
        else:
            quote = Quote.objects.get(id=quote_ref)
            user = quote.submitted_by

        chat = Chat.objects.all().filter(user=user,
                                         quote_ref=quote_ref,
                                         file_name=file_name)
        context = {
            "quote_ref": quote_ref,
            "file_name": file_name,
            "uploadForm": uploadForm,
            "chatForm": chatForm,
            "chat": chat
        }
        return render(request, 'chat.html', context=context)
    else:
        html = "<html><body><h1>The page you are looking for does not exist</h1></html>"
        return HttpResponse(html)
Esempio n. 13
0
def add_post(request):
    if request.method == "POST":
        msg = request.POST.get('msgbox', None)
        c = Chat(msg_author=request.user,
                 message=msg,
                 msg_room=get_room_id(request, True))
        if msg != '':
            c.save()
        return JsonResponse({'msg': msg, 'user': c.msg_author.username})
    else:
        return HttpResponse('Request must be POST.')
Esempio n. 14
0
 def create(self, validated_data):
     print(validated_data)
     participants = validated_data.pop('participants')
     band = validated_data.pop('band')
     chat = Chat(band=band)
     chat.save()
     for username in participants:
         contact = get_user_contact(username)
         chat.participants.add(contact)
     chat.save()
     return chat
Esempio n. 15
0
def save_msg(request):
    if request.method == 'POST':
        time=datetime.datetime.now(tz=timezone.utc)
        chat = Chat(
            sender=request.data['sender'],
            receiver=request.data['receiver'],
            msg=request.data['msg'],
            time=time
            )
        chat.save();
        data={
            'status': 'true'
        }
        return Response(data, status=status.HTTP_200_OK)
Esempio n. 16
0
    async def post(self) -> Union[web.json_response, web.HTTPException]:
        """
        Find all messages by chat_id and move it into Chat container object.
        Returns: JSON compiled from Chat object or HTTPException.

        """
        chat_id = int(self.request.match_info.get('chat_id'))

        chat = await self.request.app['db'].chats.find_one(
            {"chat_id": chat_id})
        if not chat:
            raise web.HTTPNotFound(text="Empty chat")
        chat = Chat(**clean_data(chat))
        await chat.fetch_messages(self.request.app['db'])
        return web.json_response(chat.to_dict(), status=200)
Esempio n. 17
0
def home(request):
    global aiml_handle
    Chat.objects.all().delete()
    aiml_generate(aiml_handle)
    print "in home successfull"
    chats = Chat.objects.all()
    ctx = {
        'home': 'active',
        'chat': chats
    }
    if request.user.is_authenticated:
        intro = "Welcome to KR food delivery. Order and eat Great food.Please Pick a Food Category"
        chat_message = Chat(user=request.user, message=intro, human_bot=False)
        chat_message.save()
        msg = "show me the categories"
        response = aiml_handle.respond(preprocess_data(msg))
        if response[0] == '@':
            result_list = database_fetch(response[1:])
            result = json_html(result_list)
        chat_message = Chat(user=request.user, message=result, human_bot=False)
        chat_message.save()
        return render(request, 'order_message.html', ctx)
    else:
        return render(request, 'base.html', None)
Esempio n. 18
0
def CreateChatView(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        if name == '':
            return HttpResponseRedirect(reverse('chat:chat'))
        chat = Chat()
        chat.admin = get_object_or_404(Profile, user=request.user)
        chat.name = name
        chat.image = request.FILES.get('image')
        chat.save()

        chat.users.add(get_object_or_404(Profile, user=request.user))
        chat.save()

    return HttpResponseRedirect(reverse('chat:open_chat', args=(chat.pk, )))
Esempio n. 19
0
def startChat(request):
    if request.method == 'POST':
        message = request.POST.get('message')
        sender = request.POST.get('sender')
        receiver = request.POST.get('receiver')
        key = request.POST.get('key')

        chat = Chat(sender=sender, receiver=receiver, key=key, message=message)
        notif = Notification(
            user=User.objects.get(email=receiver),
            contact=request.user.username,
            body="You've just received a message from {0}".format(sender))

        chat.save()
        notif.save()
        return HttpResponse('successfuly sent message')
 def create(self, validated_data):
     participants = validated_data.pop('participants')
     chat = Chat()
     chat.save()
     curr_user = self.context['request'].user
     if (len(Contact.objects.filter(user=curr_user)) == 0):
         Contact.objects.create(user=curr_user)
     usernames=''   
     for username in participants:
         contact = get_user_contact(username)
         chat.participants.add(contact)
         usernames += username.capitalize() + '_'
     usernames=usernames[:-1]
     chat.memebers_name=usernames
     chat.save()
     return chat
Esempio n. 21
0
def Post(request, username):

    if request.method == "POST":
        sender = request.user
        msg = request.POST.get('msgbox', None)

        receiver = username

        if msg != '':
            s1 = User.objects.get(username=sender)
            r1 = User.objects.get(username=receiver)
            c = Chat(message=msg, sender=s1, receiver=r1)
            c.save()

        return JsonResponse({'msg': msg})
    else:
        return HttpResponse('Request must be POST.')
    def create_chat(self, request):
        user=request.user
        try:
            chat = Chat(
                creator=request.user,
                chat_label=request.data['chat_label'],)
            chat.save()

            member = Member(
                chat=chat,
                user=request.user,
            )
            member.save()

            serializer = ChatSerializer(chat)
            return Response({'chats': {serializer.data['id']: serializer.data}}, status=status.HTTP_200_OK)
        except KeyError:
            return Response({}, status=status.HTTP_400_BAD_REQUEST)
Esempio n. 23
0
def save_feersum_message(data: dict):
    pages = data.get('content', {}).get('channel_data', {}).get('pages', [])

    if pages:
        for page in pages:
            title = page.get('title', 'No Title')
            content = page['text']
            if page.get('buttons'):
                for btn in page.get('buttons'):
                    content += f"\n{btn.get('text')}"
            obj = {
                "title": title,
                "content": content,
                "send_to": CHANNEL,
                "address": "Feersum",
                "channel": CHANNEL,
                "uid": str(uuid4())
            }
            instance = Chat(**obj)
            instance.save()
Esempio n. 24
0
 def get(self, request, user):
     form = self.form_class
     chat = Chat.objects.filter(invited=user).filter(
         invited=request.user.id)
     if chat.values():
         messages = Message.objects.filter(
             chat=chat.values()[0]['chat_id']).order_by('date')
     else:
         user1 = User.objects.get(pk=user)
         user2 = User.objects.get(pk=request.user.id)
         while True:
             id = random.randint(0, 999999)
             if not Chat.objects.filter(pk=id).exists():
                 chat = Chat(chat_id=id, admin=user2)
                 break
         print(chat.date)
         chat.save()
         chat.invited.add(user1)
         chat.invited.add(user2)
         messages = []
     return redirect(f'/chat/{chat.chat_id}')
Esempio n. 25
0
def upload(request):
    customHeader = request.META['HTTP_MYCUSTOMHEADER']

    # obviously handle correct naming of the file and place it somewhere like media/uploads/
    filename = str(Chat.objects.count())
    filename = filename + "name" + ".wav"
    uploadedFile = open(filename, "wb")
    # the actual file is in request.body
    uploadedFile.write(request.body)
    uploadedFile.close()
    # put additional logic like creating a model instance or something like this here
    r = sr.Recognizer()
    harvard = sr.AudioFile(filename)
    with harvard as source:
        audio = r.record(source)
    msg = r.recognize_google(audio)
    os.remove(filename)
    chat_message = Chat(user=request.user, message=msg)
    if msg != '':
        chat_message.save()
    return redirect('/')
def getChatId(username1, username2):
    user1Chats = Chat.query.filter(
        or_(Chat.user1 == username1, Chat.user2 == username1)).all()
    print("User1Chats:")
    foundChat = None
    for chat in user1Chats:
        if chat.user1 == username2:
            foundChat = chat.id
            break
        if chat.user2 == username2:
            foundChat = chat.id
            break
    if foundChat is None:
        newChat = Chat(user1=username1, user2=username2)
        chatDB.session.add(newChat)
        chatDB.session.commit()
        user1Chats = Chat.query.filter(
            or_(Chat.user1 == username1, Chat.user2 == username1)).all()
        print("User1Chats:")
        for chat in user1Chats:
            if chat.user1 == username2:
                foundChat = chat.id
                break
            if chat.user2 == username2:
                foundChat = chat.id
                break

    messages = ChatHistory.query.filter(ChatHistory.chatID == foundChat).all()
    messagesJSON = "["
    for message in messages:
        messagesJSON += ChatHistory.serialize(message) + ","
    messagesJSON = messagesJSON[:-1]
    messagesJSON += "]"

    print("{{\"id\":\"{}\",\"messages\":{}}}".format(foundChat, messagesJSON))
    if len(messages) > 0:
        return "{{\"id\":\"{}\",\"messages\":{}}}".format(
            foundChat, messagesJSON)
    else:
        return "{{\"id\":\"{}\"}}".format(foundChat)
Esempio n. 27
0
    def setUp(self):
        self.user = User.objects.create_user(username='******', password='******')
        self.client.login(username='******', password='******')

        self.course = Course(title='test_title', addedBy=self.user)
        self.course.save()

        self.unit = Unit(title='test unit title', addedBy=self.user)
        self.unit.save()

        self.course_unit = CourseUnit(course=self.course, unit=self.unit, order=0, addedBy=self.user)
        self.course_unit.save()

        self.role = Role(course=self.course, user=self.user, role=Role.INSTRUCTOR)
        self.role.save()

        self.enroll = EnrollUnitCode.get_code_for_user_chat(self.course_unit, True, self.user)

        self.history_live_chat = Chat(
            user=self.user,
            is_live=True,
            enroll_code=self.enroll
        )
        self.history_live_chat.save()
Esempio n. 28
0
def dashboard(request):
  user=request.user
  traveller_user=get_object_or_404(Traveller, email=user)
  bio = traveller_user.bio.split('.',5)
  bio_first = ". ".join(bio[:5])+(".")
  traveller_reviews = Traveller_Review.objects.all().filter(traveller=traveller_user)
  guide_user = Guide.objects.all().filter(email=user).first()
  guide_reviews = Guide_Review.objects.all().filter(guide=user)
  notifications = Notification.objects.all().filter(receiver_email=user).order_by('-reg_date')
  trip_notifications = Trip_Notification.objects.all().filter(receiver_email=user)
  guide_historys = History.objects.all().filter(guide=user,tour_complete=True)
  traveller_historys = History.objects.all().filter(traveller=user,tour_complete=True)
  ongoing_guide_tours = History.objects.all().filter(guide=user,tour_initiated=True)
  ongoing_traveller_tours = History.objects.all().filter(traveller=user,tour_initiated=True)
  if traveller_user.is_guide:
    guide_user1 = get_object_or_404(Guide, email=user)
    if guide_user1:
        trip_notifications = Trip_Notification.objects.all().filter(sender_email=user)
    
  else:
    trip_notifications = Trip_Notification.objects.all().filter(receiver_email=user)
  places = Place.objects.all()
  place_pattern=''
  for place in places:
      place_pattern = place.name+'|'+place_pattern
  
  
  context = {
                'traveller_user':traveller_user,
                'my_profile':True,
                'logged_in_user':traveller_user,   #logged_in_user is for avatar in navbar
                'guide_user' : guide_user,
                'notifications': notifications,
                'trip_notifications': trip_notifications,
                'bio_first': bio_first,
                'places' : places,
                'place_pattern' : place_pattern,
                'guide_reviews': guide_reviews,
                'guide_historys': guide_historys,
                'traveller_historys': traveller_historys,
                'g_user':guide_user,
                'guide_reviews': guide_reviews,
                'traveller_reviews': traveller_reviews, 
                'ongoing_guide_tours': ongoing_guide_tours,
                'ongoing_traveller_tours': ongoing_traveller_tours,
            }
  

  if (len(bio)>=5):
    bio_second = bio[5]
    context.update({
                'bio_second': bio_second,
                'guide_reviews': guide_reviews,
                'guide_historys': guide_historys,
                'traveller_historys': traveller_historys,
                'g_user':guide_user1,
                'traveller_reviews': traveller_reviews,  
            })
  
  if(traveller_user.is_guide):
    context.update({'g_user':guide_user1,})
 
  if (request.method == "POST" ):
    root_user = get_object_or_404(User, email=user)
    traveller_user = get_object_or_404(Traveller, email=user)
    
    if 'Update Profile' in request.POST:
      
      traveller_user.first_name = request.POST['first_name'].title()
      traveller_user.last_name = request.POST['last_name'].title()
      traveller_user.address = request.POST['address'].title()
      traveller_user.slogan = request.POST['slogan']
      traveller_user.bio = request.POST['bio']
      traveller_user.languages = request.POST['languages']
      traveller_user.gender = request.POST['gender']
        
      if request.FILES:
        traveller_user.photo_main = request.FILES['photo_main']
      
      traveller_user.save()

      root_user.first_name = request.POST['first_name'].title()
      root_user.last_name = request.POST['last_name'].title()
      print(traveller_user.photo_main)
      root_user.save()
      return redirect ('dashboard')
      
      #for guide creation form
    if 'Guide-Form' in request.POST:
      GuideView(request)  #calls guide's view in guide app

    if 'Guide-Update-Form' in request.POST:
      GuideUpdateView(request)
    
    if 'trip_reject' in request.POST:
      nid = request.POST['nid']
      t_noti = get_object_or_404(Trip_Notification, pk=nid)
      t_noti.has_rejected = True
      t_noti.save()
    
    if 'pub_off' in request.POST:
      print(request.POST)
      guide_user1.is_active = False
      guide_user1.save()
    
    if 'pub_on' in request.POST:
      print(request.POST)
      guide_user1.is_active = True
      guide_user1.save()

    #for notification
    # if 'request_guide' in request.POST:
    #   notifi    'tamt':tamt,
   
      
    # return redirect('dashboard')      sender_user = request.user

  
 
    if 'accepted' in request.POST:
      receiver_email = request.POST['receiver_email']
      receiver_user = get_object_or_404(User,email=receiver_email)
      sender_user = request.user
      sender_name = sender_user.first_name+" " +sender_user.last_name
      reg_date = datetime.datetime.utcnow().replace(tzinfo=utc)
      noti_id = request.POST['noti_id']
      noti = get_object_or_404(Notification, pk=noti_id)
      noti.completed = True
      noti.save()
      notification = Notification(receiver_email=receiver_user, sender_email=sender_user, sender_name = sender_name,is_accepted = True, reg_date= reg_date)
      notification.save()
      chat = Chat(
          sender = sender_user, receiver = receiver_user, 
          message_text = f'Hi, I\'m {sender_user.first_name} {sender_user.last_name}.\
          Thank you for choosing me to be your guide. I\'d be happy to discuss the details with you'
        )
      chat.save()
      messages.info(request, f'you can chat with {receiver_user.email} now')

    if 'ignored' in request.POST:
      noti_id = request.POST['noti_id']
      receiver_email = request.POST['receiver_email']
      receiver_user = get_object_or_404(User,email=receiver_email)
      sender_user = request.user
      sender_name = sender_user.first_name+" " +sender_user.last_name
      reg_date = datetime.datetime.utcnow().replace(tzinfo=utc)
      noti_id = request.POST['noti_id']
      noti = get_object_or_404(Notification, pk=noti_id)
      noti.completed = True
      noti.save()
      notification = Notification(receiver_email=receiver_user, sender_email=sender_user, sender_name = sender_name,is_ignored = True, reg_date= reg_date)
      notification.save()

    if 'trip_complete_by_guide' in request.POST:
      history_id = request.POST['history_id']
      history = get_object_or_404(History,pk=history_id)
      history.confirmed_by_guide=True
      if history.confirmed_by_traveller:
        history.tour_complete=True
        history.end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
      history.save()
      return redirect ('dashboard')

    if 'trip_complete_by_traveller' in request.POST:
      history_id = request.POST['history_id']
      history = get_object_or_404(History,pk=history_id)
      history.confirmed_by_traveller=True
      if history.confirmed_by_guide:
        history.tour_complete=True
        history.end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
      history.save()
      return redirect ('dashboard')

  return render(request, 'dashboard/dashboard.html',context)
Esempio n. 29
0
 def save_messages(self, message):
     sender = User.objects.get(id=self.id)
     receiver = User.objects.get(id=self.friend_id)
     hello = Chat(sender=sender, receiver=receiver, message_text=message)
     hello.save()
Esempio n. 30
0
def chat(request, email):
    friend_user = User.objects.filter(email=email).first()
    friend_userid = friend_user.id  #the one the peson is chatting with
    current_user = request.user  #logged in user
    index = 0
    user_name_chat = []

    all_chat_list = Chat.objects.filter(
        Q(sender=current_user)
        | Q(receiver=current_user))  #every chat of the logged in user
    chat_list = Chat.objects.filter(
        Q(sender=current_user, receiver=friend_userid)
        | Q(receiver=current_user,
            sender=friend_userid))  #user specific chat list

    #save message to database
    if request.method == 'POST':
        hello = Chat(sender=request.user,
                     receiver=User.objects.get(id=friend_userid),
                     message_text=request.POST['message'])
        hello.save()

    for chat in all_chat_list:
        user = chat.receiver if chat.sender == current_user else chat.sender
        if any(user == x['user'] for x in user_name_chat):
            continue
        else:
            messages = all_chat_list.filter(Q(sender=user)
                                            | Q(receiver=user)).last()
            last_message_time = messages.message_time.isoformat()
            is_last_messagebycurrentuser = True if messages.sender == current_user else False
            photo = Traveller.objects.filter(email=user).first().photo_main

            user_name_chat.append({
                'user': user,
                'messages': messages,
                'last_message': messages.message_text[:40],
                'is_last_messagebycurrentuser': is_last_messagebycurrentuser,
                'user_photo': photo,
                'last_message_time': last_message_time
            })
            print(messages.message_time.isoformat())
        # print(index)
        # print(user_name_chat[0]['is_last_messagebycurrentuser'])
        # print(user_name_chat[index]['user'])
        # print(user_name_chat[index]['last_message'])
        # print(chat_list)

        index += 1
    # sort users in order of message time
    user_name_chat = sorted(user_name_chat,
                            key=itemgetter('last_message_time'),
                            reverse=True)

    context = {
        'chat_details':
        user_name_chat,
        'chat_friend':
        User.objects.get(id=friend_userid),
        'chat_list':
        chat_list.order_by('message_time'),
        'traveller_currentuser':
        Traveller.objects.filter(email=current_user.id).first(),
        'traveller_chatuser':
        Traveller.objects.filter(email=friend_user.id).first(),
        'logged_in_user':
        Traveller.objects.filter(email=current_user.id).first(),
    }

    # print(context['traveller_currentuser'].photo_main)
    print(context['chat_friend'])

    return render(request, "chat/chat.html", context)