def profile(request, username): private_chats = None private_chat_form = None open_new_chat_form = False context = RequestContext(request) logged_user = request.user user = get_object_or_404(User, username=username) user_profile = UserProfile.objects.filter(user=user)[0] if request.user != user: private_chats = get_private_chats(request.user, user) if request.method != 'POST': new_private_chat = Chat() new_private_chat.name = "{0} <-> {1}".format(request.user.username, user.username) private_chat_form = PrivateChatForm(instance=new_private_chat) else: private_chat_form = PrivateChatForm(request.POST) if private_chat_form.is_valid(): new_private_chat = private_chat_form.save() new_private_chat.participants.add(request.user) new_private_chat.participants.add(user) new_private_chat.save() return HttpResponseRedirect("/chat/{0}".format(new_private_chat.id)) else: open_new_chat_form = True return render_to_response("django_project/profile.html", {"self": logged_user == user, "get_user": user, "user_profile": user_profile, "private_chats": private_chats, "private_chat_form": private_chat_form, "open_new_chat_form": open_new_chat_form}, context)
def start_chat(request): form = InformationForm() if request.POST: chat = Chat() form = InformationForm(request.POST) if form.is_valid(): try: operator = Operator.objects.get(id=1) except Operator.DoesNotExist: raise Http404 try: user = User.objects.get(id=1) except User.DoesNotExist: raise Http404 try: department = Department.objects.get(id=1) except Department.DoesNotExist: raise Http404 visitor = Visitor(first_name=form.cleaned_data['first_name']) visitor.save() chat = Chat(operator=operator,department=department, status='4') chat.save() return HttpResponseRedirect('/chat/view/%s/' % (chat.id)) return render_to_response('chat/start_chat.html', {"form": form})
def save_message(request): if request.method == 'POST': message_text = request.POST.get('message_text') user_id = request.POST.get('user_id') logged_user = SocialUser.objects.get(user=request.user) chat_user = SocialUser.objects.get(user=User.objects.get(id=user_id)) chat_filter = Chat.objects.filter(users=chat_user).filter(users=logged_user) if chat_filter: print "Chat instance exists!" print chat_filter for ch in chat_filter: chat_instance = ch print "--" print chat_instance print "--" else: chat_instance = Chat() chat_instance.save() chat_instance.users.add(logged_user, chat_user) print "Chat instance created" print chat_instance new_message = Message(author=logged_user, content=message_text, chat=chat_instance) new_message.save() return JsonResponse({'content': new_message.content, 'author': new_message.author.get_initials, 'author_id': new_message.author.user.id, 'timestamp': new_message.date_created_formatted}) else: return JsonResponse({'message': "You didn't send with POST method, better luck next time!"})
def on_message(self, msg): userType = self.userType if (userType == 'f'): if msg.startswith("bc~~::~~"): chatroom = Chatroom.objects.filter(chatroom_id=int(self.room))[0] notice = Notice( chatroom_id=chatroom, message=msg[8:] ) notice.save() time_stamp = notice.time_stamp parsed = model_to_dict(notice) parsed['msgtype'] = 'bc' parsed['time_stamp'] = str(time_stamp) ChatSocketHandler.send_updates(parsed, self.room) return chatroom = Chatroom.objects.filter(chatroom_id=int(self.room))[0] chatparent = Chat.objects.filter(chat_id=-1)[0] chat = Chat( user_id=self.username, chatroom_id=chatroom, message=msg, parent_id=chatparent ) chat.save() logging.info("got message %r", msg) time_stamp = chat.time_stamp parsed = model_to_dict(chat) parsed['msgtype'] = 'msg' parsed['time_stamp'] = str(time_stamp) ChatSocketHandler.send_updates(parsed, self.room)
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('ВЫ не авторизировались.')
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})
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
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 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.')
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)
def analyze_and_store_message(self, chat_id, entry): """ analyze_and_store_message - analyzes and stores a single log message @chat_id - int, the chat identifier number @entry - {"message": , "is_employee":} - JSON log entry @return - int, sentiment score for message """ score = self.get_score(entry['message']) message = Chat(chat_id=chat_id, message=entry['message'], is_employee=entry['is_employee'], score=score) message.save() return score
def message(request): if request.user.is_authenticated(): if request.method == 'POST': message = request.POST.get('message', None) message_object = Chat(user=request.user, message=message) if message != '': message_object.save() response_data = {} return JsonResponse(response_data) else: #This doesn't work. return HttpResponseRedirect('/accounts/login/') return 200
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)
def create(request): """ --- request_serializer: CreateChatSerializer """ sdata = get_validated_serializer(request=request, serializer=CreateChatSerializer).validated_data user = get_user_from_validated_data(sdata) chat = Chat() chat.name = sdata['name'] chat.save() user_ids = sdata['user_ids'] if user.pk not in user_ids: user_ids.append(user.pk) add_users_to_chat(chat, user_ids) return Response("", status=HTTP_OK)
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)
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
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
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 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, })
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
def fetch_messages(self, chatId): queryset = Chat.last_10_messages(chatId) serializer = MessageSerializer(queryset, many=True) self.send(text_data=json.dumps({ 'command': 'messages', 'messages': serializer.data }))
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)
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, )))
def edit_chat(request): if request.method == 'POST': chat_form = ChatForm(request.POST) if chat_form.is_valid(): data = chat_form.cleaned_data new_chat = Chat() new_chat.title = data.get('title') new_chat.description = data.get('description') new_chat.save() return HttpResponseRedirect('/chats/') elif request.method == 'GET': chat_template = template.loader.get_template('chat_edit.html') response_html = chat_template.render(template.RequestContext(request, {'chat_form':ChatForm()})) return HttpResponse(response_html)
def create_groupchat(request): title=request.GET['title'] owner=request.user a=Chat(owner=owner,title=title) a.save() a.users.add(owner) t={} t["type"]=0 t["pk"]= a.pk t["last_modified"]=str(a.last_modified) t["title"]=a.title t["icon"]=str(a.icon) t['users']=str(a.users.values_list('id', flat=True).order_by('id')) try: me=a.chat_messages.latest('created_at').text except: me="Start a conversation" t["message"]=me data={"chat":t,"form":{"messageform":"Group created successfully"}} return HttpResponse(json.dumps(data),content_type="application/json")
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()
def handle_message(self, message): response = {} if (self.associated_client): response['type'] = constants.SUCCESS response['name'] = self.name response['message'] = message['message'] self.associated_client.message(json.dumps(response)) else: response['type'] = constants.ERROR response['message'] = "Client not conencted" self.message(json.dumps(response)) # Save the message to the database is_employee = False if (self.client_type == constants.ENTITY_TYPE_EMPLOYEE): is_employee = True c = Chat(chat_id=self.chat_id, message=message['message'], is_employee=is_employee) c.save()
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}')
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 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 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
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
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()
def handle_uploaded_log(f, employee_id): """ Given a chat log json file it sends it to the analyzer to be analyzed and stored in the database """ # Load the json file log = json.load(f) customer_name = log[0]['customer_name'] # Create a new chat entry for the employee employee = Employee.objects.get(user__id = employee_id) employee_entry = EmployeeChatList(employee=employee, customer_name=customer_name) employee_entry.save() chat_id = employee_entry.chat_id analyzer = Analyzer() total_score = 0 # The running score of the entire chat # For each entry in the log except for the first one which contains the customer name store it for entry in log[1:]: if entry['is_employee']: message = Chat(chat_id=chat_id, message=entry['message'], is_employee=entry['is_employee']) message.save() else: score = analyzer.analyze_and_store_message(chat_id, entry) total_score += score employee_entry.score = total_score employee_entry.save() # Update the employees score employee.update_score(total_score) return chat_id
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
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
def get_context_data(self, **kwargs): if self.request.user.is_authenticated: create_action(self.request.user, 'DAILY_VISIT') context = TemplateView.get_context_data(self, **kwargs) user = self.request.user if user.is_authenticated: deals = [] for deal in user.deals: deals.append(deal.set_pov(self.request.user)) context['deals'] = deals context['user_feedback_open'] = user.userfeedback_set.filter( status=0) context['push_feedback_open'] = user.pushfeedback_set.filter( status=0) context['lobby'] = Chat.get_lobby() # context['chat'] = Chat.get_lobby() else: self.template_name = 'dashboard/dashboard_anonymous.html' return context
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)
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)
class TestCourseView(TestCase): 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() @patch('chat.serializers.ChatProgressSerializer') @patch('lms.views.get_object_or_404') @patch('lms.views.EnrollUnitCode.get_code') @patch('fsm.models.FSMState.find_live_sessions') @patch('chat.models.Chat.objects.filter') def test_course_view(self, chatFilterMock, find_live_sessions, get_code, get_obj_or_404, ChatProgressSerializer): """ This test tests that: - query FSMState.find_live_sessions(request.user).filter(activity__course=course).first() return live session and this live session is present in page's context """ filter_mock = Mock() filter_mock.filter = Mock() find_live_sessions.return_value = filter_mock first_mock = Mock() filter_mock.filter.return_value = first_mock first_mock.first = Mock() first_mock.first.return_value = Mock() first_mock.first.return_value.id = 1 unit = Mock() unit.unit.get_exercises.return_value=[Mock()] course_mock = Mock() course_units = Mock() course_mock.get_course_units = course_units course_units.return_value = [unit] get_obj_or_404.return_value = course_mock chatFilterMock = Mock() chatFilterMock.return_value = [Mock()] ChatProgressSerializer.data.get.return_value = 0 response = self.client.get(reverse('lms:course_view', kwargs={'course_id': 1})) self.assertEqual(response.status_code, 200) self.assertEqual(filter_mock.filter.call_count, 1) self.assertEqual(first_mock.first.call_count, 1) self.assertEqual(get_obj_or_404.call_count, 1) self.assertTemplateUsed(response, 'lms/course_page.html') # context should contain these keys: course, liveSession, courslets self.assertIn('course', response.context) self.assertIn('liveSession', response.context) self.assertIn('courslets', response.context) def test_course_view_negative(self): """ This test tests case when teacher not yet (opened) joined live session and student opens course page. Student should not see 'Join Live Session' button on the top of the page. """ response = self.client.get( reverse('lms:course_view', kwargs={'course_id': self.course.id}) ) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'lms/course_page.html') self.assertIn('course', response.context) self.assertIn('liveSession', response.context) self.assertIn('courslets', response.context) self.assertEqual(response.context['liveSession'], None) self.assertFalse(response.context['liveSession']) #TODO: write test when teacher really creates Course and Courslets inside of the course and student open page. #TODO: user should see 'Join' button. @patch('chat.models.Chat.get_spent_time') def test_live_chat_history_time_spent(self, get_spent_time): get_spent_time.return_value = datetime.timedelta(days=1, hours=1) response = self.client.get(reverse('lms:course_view', kwargs={'course_id': self.course.id})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'lms/course_page.html') self.assertIn('livesessions', response.context) self.assertNotEquals(response.context['livesessions'], []) self.assertEqual(response.context['livesessions'][0].get_formatted_time_spent(), '1 day, 1:00:00')
def save(self, commit=True, *args, **kwargs): if commit and self.instance.has_chat and not self.instance.chat: chat = Chat() chat.save() self.instance.chat = chat return super(TagForm, self).save(commit=commit, *args, **kwargs)
def get_context_data(self, **kwargs): context = TemplateView.get_context_data(self, **kwargs) context['lobby'] = Chat.get_lobby() return context
def post(message): uid = UserSession.get_user_id() if uid != 0: chat = Chat(message=message, user_id=uid) return chat.save() return False