Exemplo n.º 1
0
 def setUp(self):
     self.user1 = User.objects.create_user('user1', '*****@*****.**',
                                           '123456')
     self.user2 = User.objects.create_user('user2', '*****@*****.**',
                                           '123456')
     self.msg1 = Message(sender=self.user1,
                         recipient=self.user2,
                         subject='Subject Text',
                         body='Body Text')
     self.msg1.save()
Exemplo n.º 2
0
class DeleteTestCase(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user('user3', '*****@*****.**',
                                              '123456')
        self.user2 = User.objects.create_user('user4', '*****@*****.**',
                                              '123456')
        self.msg1 = Message(sender=self.user1,
                            recipient=self.user2,
                            subject='Subject Text 1',
                            body='Body Text 1')
        self.msg2 = Message(sender=self.user1,
                            recipient=self.user2,
                            subject='Subject Text 2',
                            body='Body Text 2')
        self.msg1.sender_deleted_at = datetime.now()
        self.msg2.recipient_deleted_at = datetime.now()
        self.msg1.save()
        self.msg2.save()

    def testBasic(self):
        self.assertEquals(Message.objects.outbox_for(self.user1).count(), 1)
        self.assertEquals(
            Message.objects.outbox_for(self.user1)[0].subject,
            'Subject Text 2')
        self.assertEquals(Message.objects.inbox_for(self.user2).count(), 1)
        self.assertEquals(
            Message.objects.inbox_for(self.user2)[0].subject, 'Subject Text 1')
        #undelete
        self.msg1.sender_deleted_at = None
        self.msg2.recipient_deleted_at = None
        self.msg1.save()
        self.msg2.save()
        self.assertEquals(Message.objects.outbox_for(self.user1).count(), 2)
        self.assertEquals(Message.objects.inbox_for(self.user2).count(), 2)
Exemplo n.º 3
0
 def setUp(self):
     self.user1 = User.objects.create_user('user3', '*****@*****.**',
                                           '123456')
     self.user2 = User.objects.create_user('user4', '*****@*****.**',
                                           '123456')
     self.msg1 = Message(sender=self.user1,
                         recipient=self.user2,
                         subject='Subject Text 1',
                         body='Body Text 1')
     self.msg2 = Message(sender=self.user1,
                         recipient=self.user2,
                         subject='Subject Text 2',
                         body='Body Text 2')
     self.msg1.sender_deleted_at = datetime.now()
     self.msg2.recipient_deleted_at = datetime.now()
     self.msg1.save()
     self.msg2.save()
Exemplo n.º 4
0
class SendTestCase(TestCase):
    def setUp(self):
        self.user1 = User.objects.create_user('user1', '*****@*****.**',
                                              '123456')
        self.user2 = User.objects.create_user('user2', '*****@*****.**',
                                              '123456')
        self.msg1 = Message(sender=self.user1,
                            recipient=self.user2,
                            subject='Subject Text',
                            body='Body Text')
        self.msg1.save()

    def testBasic(self):
        self.assertEquals(self.msg1.sender, self.user1)
        self.assertEquals(self.msg1.recipient, self.user2)
        self.assertEquals(self.msg1.subject, 'Subject Text')
        self.assertEquals(self.msg1.body, 'Body Text')
        self.assertEquals(self.user1.sent_messages.count(), 1)
        self.assertEquals(self.user1.received_messages.count(), 0)
        self.assertEquals(self.user2.received_messages.count(), 1)
        self.assertEquals(self.user2.sent_messages.count(), 0)
Exemplo n.º 5
0
    def save(self, sender, parent_msg=None):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []
        for r in recipients:
            msg = Message(
                sender = sender,
                recipient = r,
                subject = subject,
                body = body,
            )
            if parent_msg is not None:
                msg.parent_msg = parent_msg
                parent_msg.replied_at = timezone.now()
                parent_msg.save()
                msg.save()
                message_list.append(msg)
                signals.message_repled.send(sender=ComposeForm, message=msg, user=sender)
            else:
                msg.save()
                message_list.append(msg)
                signals.message_sent.send(sender=ComposeForm, message=msg, user=sender)

            if notification:
                if parent_msg is not None:
                    notification.send([sender], "messages_replied", {'message': msg,})
                    notification.send([r], "messages_reply_received", {'message': msg,})
                else:
                    notification.send([sender], "messages_sent", {'message': msg,})
                    notification.send([r], "messages_received", {'message': msg,})
        return message_list
Exemplo n.º 6
0
 def save(self, sender, parent_msg=None):
     if not self.user.is_active:
         return
     recipients = self.cleaned_data['recipient']
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender=sender,
             recipient=r,
             subject=subject,
             body=body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         if notification:
             if parent_msg is not None:
                 #notification.send([sender], "messages_replied", {'message': msg,}, no_django_message=True)
                 notification.send([r],
                                   "messages_reply_received", {
                                       'message': msg,
                                   },
                                   no_django_message=True)
             else:
                 #notification.send([sender], "messages_sent", {'message': msg,}, no_django_message=True)
                 notification.send([r],
                                   "messages_received", {
                                       'message': msg,
                                   },
                                   no_django_message=True)
     return message_list
Exemplo n.º 7
0
 def handle(self, *args, **options):
     translation.activate(settings.LANGUAGE_CODE)
     today = date.today()
     i = 0
     for doctor in Profile.objects.filter(role=settings.DOCTOR):
         birthdays = Profile.objects.filter(doctor=doctor.user,
                                            dob__month=today.month,
                                            dob__day=today.day)
         if birthdays:
             msg = Message()
             msg.author = doctor.user
             msg.recipient = doctor.user
             msg.subject = "%s %s/%s" % (_(u'Recordatorio de cumpleaños'),
                                         today.day, today.month)
             msg.body = _(u'Hoy es el cumpleaños de:<br></br>')
             for b in birthdays:
                 msg.body += b.get_full_name() + '<br>'
             msg.save()
             i += 1
     self.stdout.write('Sended %s birthday reminders\n' % i)
Exemplo n.º 8
0
    def save_model(self, request, obj, form, change):
        if change:
            data = {
                'url': '../../' + obj.__class__.__name__.lower() + 's/',
                'change_status': False
            }
            if 'is_active' in form.changed_data:
                data['active'] = obj.is_active
                data['change_status'] = True
            with transaction.atomic():
                message = Message()
                message.create_message_from_template(
                    template_name='ticket_answer', data=data)
                message.save()
                message.send_to_profiles(profiles=[obj.profile])

            if 'is_active' in form.changed_data and not obj.is_active:
                ticket_closed(obj)

        super(TicketMessageAdmin, self).save_model(request, obj, form, change)
Exemplo n.º 9
0
    def save(self, sender, parent_msg=None):
        recipients = self.cleaned_data['recipient']
        subject = self.cleaned_data['subject']
        body = self.cleaned_data['body']
        message_list = []
        for r in recipients:
            msg = Message(
                sender=sender,
                recipient=r,
                subject=subject,
                body=body,
            )
            if parent_msg is not None:
                msg.parent_msg = parent_msg
                parent_msg.replied_at = timezone.now()
                parent_msg.save()
                msg.save()
                message_list.append(msg)
                signals.message_repled.send(sender=ComposeForm,
                                            message=msg,
                                            user=sender)
            else:
                msg.save()
                message_list.append(msg)
                signals.message_sent.send(sender=ComposeForm,
                                          message=msg,
                                          user=sender)

            if notification:
                if parent_msg is not None:
                    notification.send([sender], "messages_replied", {
                        'message': msg,
                    })
                    notification.send([r], "messages_reply_received", {
                        'message': msg,
                    })
                else:
                    notification.send([sender], "messages_sent", {
                        'message': msg,
                    })
                    notification.send([r], "messages_received", {
                        'message': msg,
                    })
        return message_list
Exemplo n.º 10
0
def getConversation(request, conversationID):
	allconversations = ConversationLog.objects.all()
	conversations = []
	for conversation in allconversations:
		if request.user in conversation.participants.all():
			conversations.append(conversation)
	# if conversation does not exist, go back to /private_messages/
	if not ConversationLog.objects.filter(id=conversationID).exists():
		messages.error(request, "That conversation does not exist.")
		return HttpResponseRedirect("/private_messages/")

	active_conversation = ConversationLog.objects.get(pk=conversationID)
	active_conversation.readBy.add(request.user)

	if request.method == 'POST':
		form = SendMessage(request.POST)
		if form.is_valid():
			send_message = SendMessage(request.POST)
			message_content = send_message.data['content'].encode()
			message_sender = request.user
			message_receiver = active_conversation.participants.all().exclude(id=request.user.id)
			isEncrypted = False;
			try:
				isEncrypted = send_message.data['encrypted']
			except Exception:
				pass
			if isEncrypted:
				# encrypted_message = encrypt(message_content)
				# message_content = encrypt(message_content)[0]
				publickey = UserProfile.objects.get(user=message_receiver).public_key
				message_content = encrypt(message_content, publickey)
				print(message_content)
			message = Message(sender=message_sender, content=message_content, encrypted=isEncrypted)
			message.save()
			active_conversation.log.add(message)
	else:
		form = SendMessage()

	decrypted_active_conversation = []

	i = 0
	for message in active_conversation.log.all():
		if message.encrypted and request.method == 'POST' and (not request.user == message.sender) and (not request.POST.get('privatekey') == None):
			key = request.POST.get('privatekey')
			print(key)
			print("####################################################################")
			print(message.content)
			decrypted_message = decrypt(bytes(message.content), key)
			print(decrypted_message)
			m = Message(sender=message.sender, content=decrypted_message, encrypted=False)
			setattr(message, "content", decrypted_message)
			setattr(message, "encrypted", False)
			message.save()
			decrypted_active_conversation.append((bytes(m.content),m.encrypted, message.sender))
		else:
			decrypted_active_conversation.append((bytes(message.content), message.encrypted, message.sender))
		i+=1
	# if user is not in the conversation, redirect to /private_messages/
	if request.user not in active_conversation.participants.all():
		messages.error(request, "You are not in that conversation.")
		return HttpResponseRedirect('/private_messages/')
	c = Context({'conversations': conversations, 'decrypted_active_conversation': decrypted_active_conversation,
		'active_conversation': active_conversation})
	c['form'] = form
	c = RequestContext(request, c)
	return render(request, 'private_messages.html', c)
Exemplo n.º 11
0
def newConversation(request):
	#if request.method == 'POST':
	#	form = 
	#active_conversation = ConversationLog.objects.get(pk=conversationID)
	#c = Context({'conversations': conversations, 'active_conversation':active_conversation})
	if request.method == 'POST':
		conversationForm = ConversationForm()
		#if conversationForm.is_valid():
		new_conversation = ConversationForm(request.POST)
		participants = new_conversation.data['participants']
		encrypted = request.POST.get('encrypt')
		log = new_conversation.data['message']
		pattern = re.compile("^\s+|\s*,\s*|\s+$")
		if (participants != "") and (log != ""):
			users = []
			nonexistentusers = []
			for x in pattern.split(participants):
				if x:
					if x in User.objects.all().values_list('username', flat=True):
						users.append(x)
					else:
						nonexistentusers.append(x)
			if len(nonexistentusers) > 0:
				printout = "The following users do not exist: "
				for y in nonexistentusers:
					printout += y
					printout += " "
				printout += ". Please send the message again."
				return HttpResponse(printout)
			elif len(users) > 2:
				return HttpResponse("Please only enter your username and the username of the desired recipient")
			else:
				active_conversation = ConversationLog()
				active_conversation.save()
				#userobjects = []
				for x in users:
					active_conversation.participants.add(User.objects.get(username=x))
					#userobjects.append(User.objects.get(username=x))
					#p = "HELLO "
					#p+=str(currentUser)
					#return HttpResponse(p)
					#conversation.participants.add(currentUser)
				active_conversation.participants.add(User.objects.get(username=request.user))
				message_sender = request.user
				message_receiver = active_conversation.participants.all().exclude(id=request.user.id)
				if encrypted:
					publickey = UserProfile.objects.get(user=message_receiver).public_key
					message_content = encrypt(log.encode(), publickey)
					enc = True
				else:
					message_content = bytes(log, "UTF-8")
					enc = False
				message = Message(sender=message_sender, content=message_content, encrypted = enc)
				message.save()
				active_conversation.log.add(message)
				active_conversation.save()
				return HttpResponseRedirect('/private_messages')
				
			#return HttpResponse(users[0])
			#return HttpResponse([x for x in users if x])
		else:
			return HttpResponse("One or more of your fields is blank.")
			#return HttpResponse("WOAH")	
		#return HttpResponse(participants)
		#return HttpResponse("WOAH")
	else:
		conversationForm = ConversationForm()

	return render(request, 'new_conversation.html', {})
Exemplo n.º 12
0
    def send(self,
             send_inactive=False,
             mail_list=None,
             global_template_context=None):
        """
        Send mass mail.
        Read the comments to understand WHAT it does.
        :param send_inactive: added for sending mail once or on cron task. False -> once, True -> cron task
        :param mail_list: local context, dict in format {email: (first_name, last_name,[per_user_template_context])}
        :param global_template_context: template.Context instance
        :return: None 
        """
        if not self.is_active and not send_inactive:  # if is_active = False and send_inactive = False, return None
            return
        # Lock through DB from sending more than one thread at a time
        if self._lock:
            return
        translation.activate(self.template.language)
        self._lock = True
        self.save()
        server = None
        try:
            # Get Django's SMTP connection
            server = get_connection()
            server.open()

            sent_emails = []

            for email, data in self._emails(mail_list).iteritems():
                # send to internal messages
                if self.send_in_private:
                    log.debug('Sending message (campaign_id %s) to %s' %
                              (self.pk, email))
                    users = User.objects.filter(email=email)
                    if users:
                        user = users[0]
                        if not user.received_messages.filter(
                                campaign=self).exists():
                            context = template.Context({
                                'first_name':
                                user.first_name,
                                'last_name':
                                user.last_name
                            })
                            subject = template.Template(
                                self.email_subject).render(context).encode(
                                    'utf-8')
                            message_private_office = Message(campaign=self,
                                                             recipient=user,
                                                             subject=subject)
                            message_private_office.save()

                            self.po_sent_count += 1
                            self.save()
                    else:
                        log.exception(
                            'Error while sending message to %s: no profile' %
                            email)
                # if we should send
                if self.send_email:

                    if not email_re.match(email):  # if email validation failed
                        log.error(
                            'Email %s does not look like an email, skipping' %
                            email)
                        continue

                    # Check twice, that we haven't sent the message yet
                    # FIXME:
                    # This creates some overhead, but it is a quick way to solve
                    # concurrency problems
                    if self.sent_messages.filter(email=email).exists():
                        continue

                    if len(data) > 2:
                        # local context is specific for this email and is set at mail_list,
                        # global context is the same for all emails and is set at send
                        first_name, last_name, per_user_template_context = data
                        # {per_user_template_context} is local_context here, template.Context instance
                    else:
                        first_name, last_name = data
                        per_user_template_context = None

                    context = self.get_context(first_name, last_name, email)

                    if global_template_context is not None:  # template.Context instance
                        context.update(global_template_context)
                    if per_user_template_context is not None:
                        context.update(per_user_template_context)

                    # Make separate contexts for html and text versions
                    context_text, context_html = self._get_block_context(
                        context)

                    if self.custom_email_from:
                        email_from = "%s <%s>" % (self.custom_email_from_name,
                                                  self.custom_email_from)
                        reply_to = self.custom_email_from
                    else:
                        email_from = settings.MASSMAIL_DEFAULT_FROM_EMAIL
                        reply_to = settings.MASSMAIL_DEFAULT_REPLY_TO

                    # Create a proper MIME/Multipart email and send it
                    msg = self.template.create_email(
                        context,
                        context_text=context_text,
                        context_html=context_html,
                        subject=self.email_subject,
                        html_processor=lambda text: self.process_html(
                            text, email=email),
                        email_to=email,
                        email_from=email_from,
                        reply_to=reply_to,
                        connection=server,
                        msgtype='massmail_campaign_{}'.format(self.pk),
                    )

                    log.debug('Sending email (campaign_id %s) to %s' %
                              (self.pk, email))
                    try:
                        msg.send()  # Django builtin method to send emails
                    except smtplib.SMTPRecipientsRefused:
                        log.exception('Error while sending to email %s' %
                                      email)
                        continue
                    sent_emails.append(email)
                    SentMessage.objects.create(campaign=self, email=email)

            self.is_active = False
            self.is_sent = True
        finally:
            if server is not None:
                server.close()
            self._lock = False
            self.save()