def make_connection(request): user = request.user mentor = request.POST.get('to', None) mentor_object = User.objects.get(username=mentor) mentor_id = mentor_object.id subject = "Possible mentee connection from MentorMe" message = request.POST.get('message') sender = request.user.email if user != mentor_object: Message.send_message(user, mentor_object, message) recipient = [mentor_object.email] try: if user.profile.role == 'mentor': new_connection = Connection(user=user, mentor=mentor_id, status=1) new_connection.save() else: new_connection = Connection(user=user, mentor=mentor_id) new_connection.save() send_mail(subject, message, sender, recipient) except Exception: return HttpResponse('invalid header found') data = { 'confirm': 'Connection complete', } return redirect('/mentoring/{0}/'.format(mentor))
def new(request): if request.method == 'POST': from_user = request.user to_user_username = request.POST.get('to') try: to_user = User.objects.get(username=to_user_username) except Exception: try: to_user_username = to_user_username[ to_user_username.rfind('(') + 1:len(to_user_username) - 1] to_user = User.objects.get(username=to_user_username) except Exception: return redirect('/messages/new/') message = request.POST.get('message') if len(message.strip()) == 0: return redirect('/messages/new/') if from_user != to_user: Message.send_message(from_user, to_user, message) return redirect('/messages/{0}/'.format(to_user_username)) else: conversations = Message.get_conversations(user=request.user) return render(request, 'messenger/new.html', {'conversations': conversations})
def new(request): if not request.user.is_authenticated(): return render(request, 'authentication/login.html') else: if request.method == 'POST': from_user = request.user to_user_username = request.POST.get('to') try: to_user = User.objects.get(username=to_user_username) except Exception: try: to_user_username = to_user_username[ to_user_username.rfind('(') + 1:len(to_user_username) - 1] to_user = User.objects.get(username=to_user_username) except Exception: return redirect('/messages/new/') message = request.POST.get('message') objet = request.POST.get('objet') url = request.POST.get('url') if not url: produit = None else: produit = Produit.objects.get(pk=url) if len(message.strip()) == 0: return redirect('/messages/new/') if from_user != to_user: Message.send_message(from_user, to_user, message, objet, produit) id_boutique = request.GET.get('boutic') return redirect('/messages/{0}/?too={1}'.format( to_user_username, to_user_username)) else: id_boutique = request.GET.get('boutic') conversations = Message.get_conversations(user=request.user) if not Utilisateur.objects.filter(user=request.user).exists(): produituser = Produit.objects.filter(boutique_id=id_boutique) return render(request, 'messenger/new.html', { 'conversations': conversations, 'produituser': produituser }) else: produituser = Produit.objects.filter( boutique__user__username=request.user) return render(request, 'messenger/new.html', { 'conversations': conversations, 'produituser': produituser })
def test_sending_new_message(self): new_message = Message.send_message(self.other_user, self.user, "A short message") self.assertTrue(isinstance(new_message, Message)) self.assertEqual( Message.get_conversations(self.other_user)[0]['last'], new_message.date) self.assertEqual(new_message.message, "A short message")
def test_return_values(self): self.assertEqual(str(self.message_one), "A not that long message") self.assertEqual(self.message_one.message, "A not that long message") self.assertEqual(self.message_three.message, "A shorter message") self.assertEqual( Message.get_conversations(self.user)[0]['last'], self.message_two.date) self.assertEqual( Message.get_conversations(self.other_user)[0]['last'], self.message_three.date)
def create(self, request): channel_pk = request.POST['channel'] message = request.POST['message'] channel_object = Channel.objects.get(pk=channel_pk) newMessage = Message( user=request.user, channel=channel_object, message=message, ) newMessage.save() return HttpResponse(status=201)
def attache_image(request): if request.method == 'POST': from_user = request.user to_user_username = request.POST.get('to1') to_user = User.objects.get(username=to_user_username) form = AttacheForm(request.POST or None, request.FILES or None) attache = form.save(commit=False) msg = Message.send_message(from_user=from_user, to_user=to_user, message=None, objet=None, produit=None) attache.message = msg attache.save() print("ok!") to_user_username = request.POST.get('to') url = request.POST.get('url') id_boutique = request.GET.get('boutic') return render(request, 'messenger/includes/partial_message.html', {'message': msg}) else: return HttpResponseBadRequest()
def messages(request, username): conversations = Message.get_conversations(user=request.user) active_conversation = username messages = Message.objects.filter(user=request.user, conversation__username=username) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == username: conversation['unread'] = 0 boutique_use = request.GET.get('too') if not Utilisateur.objects.filter(user=request.user).exists(): produituser = Produit.objects.filter( boutique__user__username=boutique_use) return render( request, 'messenger/inbox.html', { 'messages': messages, 'active': active_conversation, 'conversations': conversations, 'produituser': produituser }) else: produituser = Produit.objects.filter( boutique__user__username=request.user) return render( request, 'messenger/inbox.html', { 'messages': messages, 'active': active_conversation, 'conversations': conversations, 'produituser': produituser })
def compose(msg_title=None, msg_recipient=None): user = current_user() if request.method == 'POST': # retrieve form data args = { 'recipient': request.form.get('recipient', type=str), 'title': request.form.get('title', type=str), 'body': request.form.get('body', type=str), } # ensure fields are present and within database limits if any(x == None for x in args.values()): flash('All fields are required', 'alert-danger') elif any(len(x) > Model.TEXT_MAX_LEN for x in args.values()): flash( 'Fields may not exceed {} characters'.format( Model.TEXT_MAX_LEN), 'alert-danger') # check if recipient exists elif not User.find(args['recipient']): flash("Recipient doesn't exist", 'alert-danger') # create new message else: message = Message.insert(sender_name=user.username, recipient_name=args['recipient'], date=get_current_timestamp(), title=args['title'], body=args['body']) flash('Message successfully sent', 'alert-success') return render_template('compose.html', title='New message', user=user, msg_title=msg_title, msg_recipient=msg_recipient)
def setUp(self): from datetime import datetime from messenger.models import Message self.text = "Testing 1... 2... 3..." self.message = Message(name="Tester", text=self.text, time_stamp=datetime.now())
def message_delete(message_id): user = current_user() if len(message_id) > Model.TEXT_MAX_LEN: flash('Bad message ID', 'alert-danger') return redirect('/inbox') message = Message.select(message_id) if not message: flash("Message doesn't exist", 'alert-danger') elif message.recipient_name != user.username: flash("Can't delete messages from other users", 'alert-danger') else: Message.delete(message.id) flash('Message successfully deleted', 'alert-success') return redirect('/inbox')
def post(self, request): if request.user.is_authenticated: user = get_object(Account, request.user.id) team = user.team_set.all() channel = Channel.objects.get(id=request.POST.get('channel_id', '')) thread = Thread() thread.name = request.POST.get('name', '') thread.save() thread.channel.add(channel) thread.save() message = Message() message.sender = user message.thread = thread message.text = request.POST.get('text', '') message.save() afres = {} afres['tread_id'] = thread.id afres['tread_name'] = thread.name afres['channel_id'] = channel.id afres['partner'] = message.sender.fio() afres['text'] = message.text return JsonResponse(afres)
def handle(self, *args, **options): faker = Faker("en_US") self.stdout.write("Start filling data") users = [] for index in range(options["len"]): self.stdout.write(f"Process {index} line of User") user, _ = User.objects.get_or_create( username=faker.profile()["username"]) user.first_name = faker.first_name() user.last_name = faker.last_name() user.email = faker.email() user.set_password("1234") user.save() users.append(user) for index in range(options["len"]): random_range = randrange(1000) self.stdout.write(f"Process {index} line of Chat -> " f"Message {random_range} ->? File") chat = Chat() chat.title = faker.sentence()[0:40] chat.creator = choice(users) chat.save() for _ in range(random_range): message = Message() message.sender = choice(users) message.chat = chat message.message = faker.text() message.save() if choice([True, False, False, False]): image_file = io.BytesIO() image = Image.new( "RGBA", size=(100, 100), color=( randrange(255), randrange(255), randrange(255), ), ) image.save(image_file, "png") image_file.name = "test.png" image_file.seek(0) file = File() file.document = files.File(image_file) file.message = message file.save() self.stdout.write("End filling data")
def post(self, request, *args, **kwargs): data = request.data to_user_username = data.get('to') message = data.get('message') from_user = self.request.user to_user = User.objects.filter(username=to_user_username) if to_user.count() == 1: if from_user != to_user: chat_msg = Message.send_message(from_user, to_user, message) # Return data serialized using new MessageSerializer return Response({"to": to_user, "message": message}) return Response({"detail": "User does not exists."}, status=401)
def send(request): if request.method == 'POST': from_user = request.user to_user_username = request.POST.get('to') to_user = User.objects.get(username=to_user_username) message = request.POST.get('message') if len(message.strip()) == 0: return HttpResponse() if from_user != to_user: msg = Message.send_message(from_user, to_user, message) return render(request, 'messenger/includes/partial_message.html', {'message': msg}) return HttpResponse() else: return HttpResponseBadRequest()
def u_messages(request, username): conversations = Message.get_conversations(user=request.user) active_conversation = username messages = Message.objects.filter(user=request.user, conversation__username=username) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == username: conversation['unread'] = 0 return render(request, 'mentoring/profile.html', { 'messages': messages, 'conversations': conversations, 'active': active_conversation })
def messages(request, username): conversations = Message.get_conversations(user=request.user) users_list = User.objects.filter( is_active=True).exclude(username=request.user).order_by('username') active_conversation = username messages = Message.objects.filter(user=request.user, conversation__username=username) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == username: conversation['unread'] = 0 return render(request, 'messanger/inbox.html', { 'messages': messages, 'conversations': conversations, 'users_list': users_list, 'active': active_conversation })
def message_reply(message_id): user = current_user() if len(message_id) > Model.TEXT_MAX_LEN: flash('Bad message ID', 'alert-danger') return redirect('/inbox') message = Message.select(message_id) if not message: flash("Message doesn't exist", 'alert-danger') return redirect('/inbox') elif message.recipient_name != user.username: flash("Can't view messages from other users", 'alert-danger') return redirect('/inbox') return redirect('/compose?title={}&recipient={}'.format( 'Re: {}'.format(message.title), message.sender_name))
def u_inbox(request): conversations = Message.get_conversations(user=request.user) active_conversation = None messages = None if conversations: conversation = conversations[0] active_conversation = conversation['user'].username messages = Message.objects.filter(user=request.user, conversation=conversation['user']) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == active_conversation: conversation['unread'] = 0 return render(request, 'mentoring/profile.html', { 'messages': messages, 'conversations': conversations, 'active': active_conversation })
def respond(request): saved = False people = 0 sessions = 0 message = '' if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): user_sender = User.objects.get(pk=request.POST['id_sender']) user_receiver = User.objects.get(pk=request.POST['id_receiver']) sent = True people = form.cleaned_data['people'] sessions = form.cleaned_data['sessions'] message = form.cleaned_data['message'] bm = Message() bm.id_sender = user_sender bm.id_receiver = user_receiver bm.message = message bm.people = people bm.sessions = sessions bm.save() mail_data = {} mail_data['subject'] = ' %s %s is Interested in you.' % (user_sender.first_name, user_sender.last_name) mail_data['message'] = ''' %s %s, <br> %s %s is Interested in talking to you. To answer check your inbox.<br> <h3>People: %s</h3> <br> <h3>Sessions: %s</h3> <br> <h3>Details: </h3><br> %s ''' % (user_receiver.first_name, user_receiver.last_name, user_sender.first_name, user_sender.last_name, people, sessions, message) mail_data['from'] = '*****@*****.**' mail_data['sender'] = user_sender.email mail_data['receiver'] = user_receiver.email sent = utils.send_mail(mail_data) saved = True return HttpResponseRedirect('/search/') else: return HttpResponseRedirect('/')
def messages_view(request): if request.user.is_authenticated: users = [contact.user for contact in request.user.contacts.all()] users = build_paginator(request, users) last_messages = [] for user in users: message = Message.get(user1=user, user2=request.user) last_messages.append({ 'user': user, 'message': message.last() if message else [], }) return render( request, 'messenger/messages.html', { 'title': _('Messages'), 'datetime': timezone.now(), 'users': users, 'last_messages': last_messages, }) else: return redirect('login')
def inbox2(request): conversations = Message.get_conversations(user=request.user) users_list = User.objects.filter() active_conversations = None messages = None if conversations: conversation = conversations[0] active_conversations = conversation['user'].username messages = Message.objects.filter(user=request.user, conversation=conversation['user']) messages.update(is_read=True) for conversation in conversations: if conversation in conversations: if conversation['user'].username == active_conversations: conversation['unread'] = 0 return render(request, 'messanger/inbox.html', { 'messages': messages, 'conversations': conversations, 'users_list': users_list, 'active': active_conversations })
def send(request): if request.method == 'POST': from_user = request.user to_user_username = request.POST.get('to') to_user = User.objects.get(username=to_user_username) message = request.POST.get('message') print("okkkk") if len(message.strip()) == 0: return HttpResponse() if from_user != to_user: #form = AttachementForm(request.POST, request.FILES) #image = form.save(commit=False) msg = Message.send_message(from_user, to_user, message, None, None) return render(request, 'messenger/includes/partial_message.html', {'message': msg}) return HttpResponse() else: return HttpResponseBadRequest()
def receive(self, text_data): data = json.loads(text_data) chat_obj = Chat.objects.get(pk=data['chat']) sender = chat_obj.group.users.all().filter(username=self.user_name) if chat_obj and sender: sender = sender[0] datetimeObj = datetime.now() created_time = datetimeObj.strftime("%b %d %Y %I:%M%p") # set last chat used by user. sender.selected_chat = chat_obj sender.save() # Save message to database message_obj = Message() # sender is in list format, get first sender message_obj.sender = sender message_obj.chat = chat_obj message_obj.text = data['message'] if 'image' in data: # Generate a unique file name chars = string.ascii_letters + string.digits + '!@#$%^&*()' random.seed = (os.urandom(1024)) filename = ''.join(random.choice(chars) for i in range(23)) # Save to message object message_obj.image = base64_file(data=data['image'], name=filename) message_obj.save() # Emit message to online users for user in chat_obj.group.users.all(): async_to_sync(self.send_user_message)(user.username, message_obj, created_time)
def get_messages_view(request, pk): if request.user.is_authenticated: if request.user.pk != pk: user = get_object_or_404(User, pk=pk) messages = Message.get(user1=user, user2=request.user) messages = build_paginator(request, messages) for message in messages: if not message.received and message.receiver == request.user: message.received = True message.date_received = timezone.now() message.save() return render( request, 'messenger/get_messages.html', { 'title': _('Messages'), 'messages': messages, 'datetime': timezone.now(), 'user': user, }) else: return redirect('home') else: return redirect('login')
def inbox(request): conversations = Message.get_conversations(user=request.user) active_conversation = None messages = None produituser = Produit.objects.filter(boutique__user_id=request.user.id) if conversations: conversation = conversations[0] active_conversation = conversation['user'].username messages = Message.objects.filter(user=request.user, conversation=conversation['user']) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == active_conversation: conversation['unread'] = 0 return render( request, 'messenger/inbox.html', { 'produituser': produituser, 'messages': messages, 'conversations': conversations, 'active': active_conversation })
def message_id(message_id): user = current_user() if len(message_id) > Model.TEXT_MAX_LEN: flash('Bad message ID', 'alert-danger') return redirect('/inbox') message = Message.select(message_id) if not message: flash("Message doesn't exist", 'alert-danger') return redirect('/inbox') elif message.recipient_name != user.username: flash("Can't view messages from other users", 'alert-danger') return redirect('/inbox') sender = '{}'.format(User.select(message.sender_name)) return render_template('message_id.html', title=message.title, user=user, message=message, sender=sender)
def send2(request): if request.method == 'POST': from_user = request.user to_user_username = request.POST.get('to') print(to_user_username) to_user = User.objects.get(username=to_user_username) print(to_user) objet = request.POST.get('objet') url = request.POST.get('url') print(url) produit = Produit.objects.get(pk=url) print(produit.title) if from_user != to_user: msg = Message.send_message(from_user, to_user, "", objet, produit) return render(request, 'messenger/includes/partial_message.html', {'message': msg}) else: return HttpResponseBadRequest()
def send_message(thread_id, sender_id, message_text, sender_name=None): message = Message() message.text = message_text message.thread_id = thread_id message.sender_id = sender_id message.save()
def messages(request, username): if request.method == 'GET': conversations = Message.get_conversations(user=request.user) users_list = User.objects.filter(is_active=True).exclude( username=request.user).order_by('username') active_conversation = username messages = Message.objects.filter(user=request.user, conversation__username=username) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == username: conversation['unread'] = 0 return render( request, 'messenger/inbox.html', { 'messages': messages, 'conversations': conversations, 'users_list': users_list, 'active': active_conversation }) else: from_user = request.user to_user = User.objects.get(username=username) message = request.POST.get('message') if request.POST.get("document") is None: save_path = os.path.join('sent_docs/', request.FILES['document'].name) doc = default_storage.save(save_path, request.FILES['document']) msg = Message.send_message(from_user, to_user, message, doc) conversations = Message.get_conversations(user=request.user) users_list = User.objects.filter(is_active=True).exclude( username=request.user).order_by('username') active_conversation = username messages = Message.objects.filter(user=request.user, conversation__username=username) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == username: conversation['unread'] = 0 return render( request, 'messenger/inbox.html', { 'messages': messages, 'conversations': conversations, 'users_list': users_list, 'active': active_conversation, }) else: doc = None msg = Message.send_message(from_user, to_user, message, doc) conversations = Message.get_conversations(user=request.user) users_list = User.objects.filter(is_active=True).exclude( username=request.user).order_by('username') active_conversation = username messages = Message.objects.filter(user=request.user, conversation__username=username) messages.update(is_read=True) for conversation in conversations: if conversation['user'].username == username: conversation['unread'] = 0 return render( request, 'messenger/inbox.html', { 'messages': messages, 'conversations': conversations, 'users_list': users_list, 'active': active_conversation, })
def view(request, id, idP="1"): # print str(id) Ptype = request.GET.get('Ptype', 'all') #print Ptype Prange = request.GET.get('Prange', 'all') #print Prange store = Store.objects.get(id=id) # send message to store's owner if request.user != store.user: if (not (request.user in store.visitors.all())): print("visit ...") message = "This is an automatically generated message, welcome to my store ( " + str( store.name ) + " ) , if you have any questions, please feel free :) " if store.user.profile.message != None: message = str(store.user.profile.message) msg = Message.send_message(store.user, request.user, message).save() store.visitors.add(request.user) products = store.product_set.all().order_by("-created_at") Pmin = request.GET.get('Pmin', 0) Pmax = request.GET.get('Pmax', 10000) products = products.filter(price__gte=Pmin) products = products.filter(price__lte=Pmax) if (Ptype == "handMade"): products = products.filter(Ptype=1) if (Ptype == "vintage"): products = products.filter(Ptype=2) nP = products.count() imgs = StoreImage.objects.filter(store=store).order_by("-created_at") pages = Paginator(products, 9) vId = int(idP) if ((vId > int((nP + 8) / 9)) or (vId < 1)): vId = 1 page = pages.page(vId) values = [] for product in page: x = getMainImage(product) #print x values.append((product, x, product.likes.all(), product.smiles.all(), product.wishes.all(), product.likes.count() + product.smiles.count() + product.wishes.count())) intList = list(range(1, ((products.count() + 8) / 9) + 1)) idList = [] for i in intList: idList.append(str(i)) filters = "?Ptype=" + str(Ptype) + "&Pmin=" + str(Pmin) + "&Pmax=" + str( Pmax) context = { 'flag': 'yes', 'store': store, 'values': values, 'page': page, 'nP': nP, 'Pmin': Pmin, 'Pmax': Pmax, 'idList': idList, 'pageId': str(vId), 'filters': filters, 'Ptype': str(Ptype), 'Prange': str(Prange), 'idS': str(id), 'nC1': getCount(categoriesList[0]), 'nC2': getCount(categoriesList[1]), 'nC3': getCount(categoriesList[2]), 'nC4': getCount(categoriesList[3]), 'nC5': getCount(categoriesList[4]), 'nC6': getCount(categoriesList[5]), } if imgs: context['img'] = imgs[0] return render(request, 'discover.html', context)