Beispiel #1
0
    def test_message_create_filled(self):
        message = Message()

        message.sender = self.sender
        message.title = u"title"
        message.text = u"text"

        message.save()

        message.recipients = self.recipients
        message.recipients_user = self.recipients
        message.recipients_course = self.recipients_course
        message.recipients_group = self.recipients_group

        message_id = message.id

        message = Message.objects.get(id=message_id)

        self.assertIsInstance(message, Message)
        self.assertEqual(message.sender, self.sender)
        self.assertEqual(message.title, u"title")
        self.assertEqual(message.text, u"text")
        self.assertItemsEqual(message.recipients.all(), self.recipients)
        self.assertItemsEqual(message.recipients_user.all(), self.recipients)
        self.assertItemsEqual(message.recipients_course.all(), self.recipients_course)
        self.assertItemsEqual(message.recipients_group.all(), self.recipients_group)
Beispiel #2
0
    def test_ajax_get_message_user(self):
        client = self.client

        message = Message()
        message.sender = self.sender
        message.title = u"title"
        message.text = u"text"
        message.save()
        message.recipients = self.recipients
        message.recipients_user = self.recipients_user
        message.recipients_group = self.recipients_group
        message.recipients_course = self.recipients_course

        get_data = {
            u'unread_count': 0,
            u'msg_id': 1,
            u'mailbox': 'inbox'
        }

        response_data = {
            'sender': {
                'url': self.sender.get_absolute_url(),
                'fullname': u'%s %s' % (self.sender.last_name, self.sender.first_name),
                'id': self.sender.id,
                'avatar': ''
            },
            'unread_count': 0,
            'text': message.text,
            'date': message.create_time.astimezone(
                timezone_pytz(self.sender.get_profile().time_zone)
            ).strftime("%d.%m.%y %H:%M:%S"),
            'recipients_course': [{
                'url': self.recipients_course[0].get_absolute_url(),
                'name': self.recipients_course[0].name,
                'id': self.recipients_course[0].id
            }],
            'recipients_group': [{
                'name': self.recipients_group[0].name,
                'id': self.recipients_group[0].id
            }],
            'recipients_user': [{
                'url': self.recipients_user[0].get_absolute_url(),
                'fullname': u'%s %s' % (self.recipients_user[0].last_name, self.recipients_user[0].first_name),
                'id': self.recipients_user[0].id
            }],
            'recipients_status': []
        }

        # login
        self.assertTrue(client.login(username=self.sender.username, password=self.sender_password))

        # get page
        response = client.get(reverse('mail.views.ajax_get_message'), get_data)
        self.assertEqual(response.status_code, 200)

        self.assertEqual(json.loads(response.content), response_data)
Beispiel #3
0
def message_list(request, pk, template_name='mail/message_list.html'):
	account_data = MailAccount.objects.get(pk=pk)
	
	imap_helper = ImapHelper(account_data)
	data = {}
	data['account'] = str(account_data)

	mailbox = request.GET.get('mailbox', False)
	if mailbox is not False:
		imap_helper.select_mailbox(mailbox)
	else:
		imap_helper.select_mailbox('INBOX')
		mailbox = 'INBOX'

	try:
		mb = MailBox.objects.get(mail_account=account_data.id, name=mailbox)
	except ObjectDoesNotExist:
			mb = MailBox(name=str(mailbox), mail_account=account_data)
			mb.save()


	messages = imap_helper.load_mail_from_mailbox()
	print(messages)

	for message in messages:		
		
		check = Message.objects.filter(identifier=message['identifier'], mail_box=mb)
		
		if not check:
			m = Message(mail_box=mb, sender=message['sender'], subject=message['subject'], identifier=message['identifier'], mail_source=message['source'])
			m.save()

	ms = Message.objects.filter(mail_box=mb)

	data['object_list'] = ms

	return render(request, template_name, data)
Beispiel #4
0
def ajax_send_message(request):
    user = request.user

    data = dict(request.POST)

    hidden_copy = False
    if 'hidden_copy' in data and data['hidden_copy'][0]:
        hidden_copy = True

    variable = False
    if 'variable' in data and data['variable'][0]:
        variable = True

    message = Message()
    message.sender = user
    message.title = data['new_title'][0]
    message.text = data['new_text'][0]
    message.hidden_copy = hidden_copy
    message.variable = variable
    message.save()

    recipients_ids = set()

    if "new_recipients_user[]" in data or "new_recipients_preinit[]" in data:
        users = data.get("new_recipients_user[]", [])
        if "new_recipients_preinit[]" in data:
            users += request.session.get(
                'user_ids_send_mail_' + data["new_recipients_preinit[]"][0],
                [])
        message.recipients_user = users
        recipients_ids.update(
            message.recipients_user.values_list('id', flat=True))

    group_ids = []
    if "new_recipients_group[]" in data:
        message.recipients_group = data["new_recipients_group[]"]

        for group in Group.objects.filter(
                id__in=data["new_recipients_group[]"]):
            recipients_ids.update(
                group.students.exclude(id=user.id).values_list('id',
                                                               flat=True))
            group_ids.append(group.id)

    if "new_recipients_course[]" in data:
        message.recipients_course = data["new_recipients_course[]"]

        for course in Course.objects.filter(
                id__in=data["new_recipients_course[]"]):
            for group in course.groups.exclude(id__in=group_ids).distinct():
                recipients_ids.update(
                    group.students.exclude(id=user.id).values_list('id',
                                                                   flat=True))

    if "new_recipients_status[]" in data:
        message.recipients_status = data["new_recipients_status[]"]

        recipients_ids.update(
            UserProfile.objects.filter(
                user_status__in=data["new_recipients_status[]"]).values_list(
                    'user__id', flat=True))

    message.recipients = list(recipients_ids)

    return HttpResponse("OK")
Beispiel #5
0
    def test_message_create_filled(self):
        message = Message()

        message.sender = self.sender
        message.title = u"title"
        message.text = u"text"

        message.save()

        message.recipients = self.recipients
        message.recipients_user = self.recipients
        message.recipients_course = self.recipients_course
        message.recipients_group = self.recipients_group

        message_id = message.id

        message = Message.objects.get(id=message_id)

        self.assertIsInstance(message, Message)
        self.assertEqual(message.sender, self.sender)
        self.assertEqual(message.title, u"title")
        self.assertEqual(message.text, u"text")
        self.assertItemsEqual(message.recipients.all(), self.recipients)
        self.assertItemsEqual(message.recipients_user.all(), self.recipients)
        self.assertItemsEqual(message.recipients_course.all(),
                              self.recipients_course)
        self.assertItemsEqual(message.recipients_group.all(),
                              self.recipients_group)
Beispiel #6
0
    def test_ajax_get_message_user(self):
        client = self.client

        message = Message()
        message.sender = self.sender
        message.title = u"title"
        message.text = u"text"
        message.save()
        message.recipients = self.recipients
        message.recipients_user = self.recipients_user
        message.recipients_group = self.recipients_group
        message.recipients_course = self.recipients_course

        get_data = {u'unread_count': 0, u'msg_id': 1, u'mailbox': 'inbox'}

        response_data = {
            'sender': {
                'url':
                self.sender.get_absolute_url(),
                'fullname':
                u'%s %s' % (self.sender.last_name, self.sender.first_name),
                'id':
                self.sender.id,
                'avatar':
                ''
            },
            'unread_count':
            0,
            'text':
            message.text,
            'date':
            message.create_time.astimezone(
                timezone_pytz(self.sender.profile.time_zone)).strftime(
                    "%d.%m.%y %H:%M:%S"),
            'recipients_course': [{
                'url':
                self.recipients_course[0].get_absolute_url(),
                'name':
                self.recipients_course[0].name,
                'id':
                self.recipients_course[0].id
            }],
            'recipients_group': [{
                'name': self.recipients_group[0].name,
                'id': self.recipients_group[0].id
            }],
            'recipients_user': [{
                'url':
                self.recipients_user[0].get_absolute_url(),
                'fullname':
                u'%s %s' % (self.recipients_user[0].last_name,
                            self.recipients_user[0].first_name),
                'id':
                self.recipients_user[0].id
            }],
            'recipients_status': []
        }

        # login
        self.assertTrue(
            client.login(username=self.sender.username,
                         password=self.sender_password))

        # get page
        response = client.get(reverse(mail.views.ajax_get_message), get_data)
        self.assertEqual(response.status_code, 200)

        self.assertEqual(json.loads(response.content), response_data)
Beispiel #7
0
def paypal_ipn(request):
    """Handles PayPal IPN notifications."""
    if not request.method == 'POST':
        logging.warning('IPN view hit but not POSTed to. Attackers?')
        raise Http404
    paypal_url = settings.PAYPAL_POST_URL

    # Ack and verify the message with paypal
    params = request.POST.copy()
    if params.get('_fake_paypal_verification') == settings.SECRET_KEY:
        pass
    else:
        params['cmd'] = '_notify-validate'
        req = urllib2.Request(paypal_url, urllib.urlencode(params))
        req.add_header('Content-type', 'application/x-www-form-urlencoded')
        try:
            response = urllib2.urlopen(req)
        except urllib2.URLError:
            logging.error('Unable to contact PayPal to ack the message.')
            raise Http404 # Let PayPal resend later and try again
        if response.code != 200 or response.readline() != 'VERIFIED':
            logging.warning('IPN view could not verify the message with '
                'PayPal. Original: %r' % request.POST)
            return HttpResponse('Ok (unverified)')
    params = request.POST.copy()

    # Verify that the message is for our business
    business = params.get('business')
    if business and business != settings.PAYPAL_BUSINESS:
        logging.warning('IPN received for a random business. Weird.')
        return HttpResponse('Ok (wrong business)')

    # Save the notification and ensure it's not a duplicate
    transaction_id = params.get('txn_id')
    if not transaction_id:
        logging.warning('No transaction id provided.')
        return HttpResponse('Ok (no id)')
    try:
        record = IPNRecord(transaction_id=transaction_id, data=repr(params))
        record.save()
    except IntegrityError:
        logging.warning('IPN was duplicate. Probably nothing to worry about.')
        return HttpResponse('Ok (duplicate)')

    # Verify that the status is Completed
    if params.get('payment_status') != 'Completed':
        logging.warning('Status not completed. Taking no action.')
        return HttpResponse('Ok (not completed)')

    # Verify that the amount paid matches the cart amount
    invoice_id = params.get('invoice')
    try:
        order = Order.objects.get(invoice_id=invoice_id)
    except Order.DoesNotExist:
        logging.warning('Could not find corresponding Order.')
        return HttpResponse('Ok (no order)')
    order_total = Decimal(str(order.get_as_cart()['total'])).quantize(Decimal('0.01'))
    paypal_total = Decimal(str(params['mc_gross'])).quantize(Decimal('0.01'))
    if order_total != paypal_total:
        logging.warning('PayPal payment amount (%.2f) did not match order '
            'amount (%.2f)!' % (paypal_total, order_total))
        order.status = Order.PROCESSING_ERROR
        order.save()
        return HttpResponse('Ok (wrong amount)')

    # Take action! Save the details of the order
    order.status = Order.PAYMENT_CONFIRMED

    order.user_email = params.get('payer_email', '')
    order.user_firstname = params.get('first_name', '')
    order.user_lastname = params.get('last_name', '')
    order.user_shiptoname = params.get('address_name', '')
    order.user_shiptostreet = params.get('address_street', '')
    order.user_shiptostreet2 = ''
    order.user_shiptocity = params.get('address_city', '')
    order.user_shiptostate = params.get('address_state', '')
    order.user_shiptozip = params.get('address_zip', '')
    order.user_shiptocountrycode = params.get('address_country_code', '')
    order.user_shiptophonenum = params.get('contact_phone', '')

    order.paypal_transactionid = params.get('txn_id', '')
    order.paypal_paymenttype = params.get('payment_type', '')
    try:
        order.paypal_ordertime = datetime.strptime(params.get('payment_date'), '%H:%M:%S %b %d, %Y %Z')
    except ValueError:
        order.paypal_ordertime = None
    order.paypal_amt = params.get('mc_gross')
    order.paypal_feeamt = params.get('mc_fee')
    order.paypal_paymentstatus = params.get('payment_status', '')
    order.paypal_notetext = ''

    order.paypal_details_dump = params.urlencode()
    order.save()

    # Increment the number of products sold
    for product_in_order in order.productinorder_set.all():
        product = product_in_order.product
        product.current_quantity += product_in_order.quantity
        product.save()

    # Create a confirmation email to be sent
    context = {'order': order}
    message = Message()
    message.to_email = order.user_email
    message.from_email = settings.DEFAULT_FROM_EMAIL
    message.subject = render_to_string('mail/order_confirmation_subject.txt', context)
    message.body_text = render_to_string('mail/order_confirmation.txt', context)
    message.body_html = render_to_string('mail/order_confirmation.html', context)
    message.save()

    logging.info('PayPal payment recorded successfully.')
    return HttpResponse('Ok')
Beispiel #8
0
def ajax_send_message(request):
    user = request.user

    data = dict(request.POST)

    hidden_copy = False
    if 'hidden_copy' in data and data['hidden_copy'][0]:
        hidden_copy = True

    variable = False
    if 'variable' in data and data['variable'][0]:
        variable = True

    message = Message()
    message.sender = user
    message.title = data['new_title'][0]
    message.text = data['new_text'][0]
    message.hidden_copy = hidden_copy
    message.variable = variable
    message.save()

    recipients_ids = set()

    if "new_recipients_user[]" in data or "new_recipients_preinit[]" in data:
        users = data.get("new_recipients_user[]", [])
        if "new_recipients_preinit[]" in data:
            users += request.session.get('user_ids_send_mail_' + data["new_recipients_preinit[]"][0], [])
        message.recipients_user = users
        recipients_ids.update(message.recipients_user.values_list('id', flat=True))

    group_ids = []
    if "new_recipients_group[]" in data:
        message.recipients_group = data["new_recipients_group[]"]

        for group in Group.objects.filter(id__in=data["new_recipients_group[]"]):
            recipients_ids.update(group.students.exclude(id=user.id).values_list('id', flat=True))
            group_ids.append(group.id)

    if "new_recipients_course[]" in data:
        message.recipients_course = data["new_recipients_course[]"]

        for course in Course.objects.filter(id__in=data["new_recipients_course[]"]):
            for group in course.groups.exclude(id__in=group_ids).distinct():
                recipients_ids.update(group.students.exclude(id=user.id).values_list('id', flat=True))

    if "new_recipients_status[]" in data:
        message.recipients_status = data["new_recipients_status[]"]

        recipients_ids.update(UserProfile.objects.filter(user_status__in=data["new_recipients_status[]"])
                              .values_list('user__id', flat=True))

    message.recipients = list(recipients_ids)

    return HttpResponse("OK")
Beispiel #9
0
    def post(self, request):
        try:
            serializer = NewGuestSerializer(data=request.data)
            if serializer.is_valid():
                if request.user.id is not None:
                    profile = Profile.objects.get(user__id=request.user.id)
                    response = serializer.save(profile=profile,
                                               user=request.user)
                    if response == 0:
                        return Response(
                            {
                                'error': True,
                                'message': "ERROR_SERVER"
                            },
                            status=status.HTTP_400_BAD_REQUEST)

                    if response == -1:
                        return Response(
                            {
                                'error': True,
                                'message': "La fecha no esta disponible"
                            },
                            status=status.HTTP_400_BAD_REQUEST)

                    #send email of the reservation
                    contenido = '<h3>Su reserva ha sido exitosa</h3><br><br>'
                    contenido = contenido + "Estimado usuario(a),<br /><br /> Env&iacute;o para su informaci&oacute;n, su reserva ya se guardo</strong>."
                    contenido = contenido + '<br /><br /><br />Favor no responder este correo, es de uso informativo unicamente.<br /><br /><br />Gracias,<br /><br /><br />'
                    contenido = contenido + 'Soporte HOTEl ROCKBAI<br/>[email protected]'

                    mail = Message(remitente=EMAIL_BACKEND,
                                   destinatario=request.data["email"],
                                   asunto='Reservacion',
                                   contenido=contenido)
                    mail.simpleSend()

                    # return render(request, "login.html", {'message':"Su Registro fue exitoso"})
                    return Response({
                        'error': False,
                        'message': response
                    },
                                    status=status.HTTP_200_OK)

                return Response(
                    {
                        'error': True,
                        'message': "El usuario debe estar logueando"
                    },
                    status=status.HTTP_400_BAD_REQUEST)

            print(serializer.errors)
            return Response(
                {
                    'error': True,
                    'message': "Todos los campos son obligatorios"
                },
                status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            print(e)
            return Response({
                'error': True,
                'message': "ERROR_SERVER"
            },
                            status=status.HTTP_400_BAD_REQUEST)