Example #1
0
    def save(self, *args, **kwargs):
        "Set Resolution if selected"
        instance = super(TicketRecordForm, self).save(*args, **kwargs)
        ticket = self.ticket
        if 'resolution' in self.cleaned_data and self.cleaned_data['resolution']:
            ticket.resolution = self.cleaned_data['body']
            ticket.save()

        # Send update if notify clicked
        if 'notify' in self.cleaned_data and self.cleaned_data['notify'] and ticket.caller:
            toaddr = ticket.caller.get_email()
            if ticket.message or toaddr:
                reply = Message()
                reply.author = instance.sender
                reply.body = instance.body
                reply.auto_notify = False
                if ticket.message:
                    reply.stream = ticket.message.stream
                    reply.reply_to = ticket.message
                else:
                    reply.stream = ticket.queue.message_stream if ticket.queue else None
                    reply.title = "[#%s] %s" % (ticket.reference, ticket.name)
                reply.save()
                if not ticket.message:
                    ticket.message = reply
                reply.recipients.add(ticket.caller)
                email = EmailMessage(reply)
                email.send_email()

        return instance
Example #2
0
def mlist_view(request, mlist_id, response_format='html'):
    "Mailing List view page"

    user = request.user.get_profile()

    mlist = get_object_or_404(MailingList, pk=mlist_id)
    if not request.user.get_profile().has_permission(mlist):
        return user_denied(
            request,
            message="You don't have access to this Mailing List",
            response_format=response_format)

    if request.user.get_profile().has_permission(mlist, mode='x'):
        if request.POST:
            message = Message()
            message.author = request.user.get_profile().get_contact()
            if not message.author:
                return user_denied(
                    request,
                    message=
                    "You can't send message without a Contact Card assigned to you.",
                    response_format=response_format)
            form = MessageForm(request.user.get_profile(),
                               mlist_id,
                               None,
                               request.POST,
                               instance=message)
            if form.is_valid():
                message = form.save()
                message.set_user_from_request(request)
                message.read_by.add(user)
                return HttpResponseRedirect(
                    reverse('messaging_mlist_view', args=[mlist.id]))
        else:
            form = MessageForm(request.user.get_profile(), mlist_id)

    else:
        form = None

    messages = Object.filter_by_request(
        request,
        Message.objects.filter(reply_to__isnull=True,
                               mlist=mlist).order_by('-date_created'))
    context = _get_default_context(request)
    context.update({'messages': messages, 'form': form, 'mlist': mlist})

    return render_to_response('messaging/mlist_view',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Example #3
0
    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            self.group, created = Group.objects.get_or_create(name='test')
            duser, created = DjangoUser.objects.get_or_create(username=self.username)
            duser.set_password(self.password)
            duser.save()
            self.user, created = User.objects.get_or_create(user=duser)
            self.user.save()
            perspective, created = Perspective.objects.get_or_create(name='default')
            perspective.set_default_user()
            perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)
            
            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()   
        
            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()
            
            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()
            
            self.message = Message(title='test', body='test', author=self.contact, stream=self.stream)
            self.message.set_default_user()
            self.message.save()
                    
            self.client = Client()  
            
            self.prepared = True
Example #4
0
    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()
            
            # Create objects
            
            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()
            
            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()
                
            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)
            
            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()   
        
            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()
            
            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()
            
            self.message = Message(title='test', body='test', author=self.contact, stream=self.stream)
            self.message.set_default_user()
            self.message.save()
                    
            self.client = Client()  
            
            self.prepared = True
Example #5
0
def mlist_view(request, mlist_id, response_format='html'):
    "Mailing List view page"
    
    user = request.user.get_profile()
    
    mlist = get_object_or_404(MailingList, pk=mlist_id)
    if not request.user.get_profile().has_permission(mlist):
        return user_denied(request, message="You don't have access to this Mailing List", 
                           response_format=response_format)
        

    if request.user.get_profile().has_permission(mlist, mode='x'):
        if request.POST:
            message = Message()
            message.author = request.user.get_profile().get_contact()
            if not message.author:
                return user_denied(request, 
                                   message="You can't send message without a Contact Card assigned to you.", 
                                   response_format=response_format)
            form = MessageForm(request.user.get_profile(), mlist_id, None, request.POST, instance=message)
            if form.is_valid():
                message = form.save()
                message.set_user_from_request(request)
                message.read_by.add(user)
                return HttpResponseRedirect(reverse('messaging_mlist_view', args=[mlist.id]))
        else:   
            form = MessageForm(request.user.get_profile(), mlist_id)

    else:
        form = None
        
    messages = Object.filter_by_request(request, 
                                        Message.objects.filter(reply_to__isnull=True, 
                                                               mlist=mlist).order_by('-date_created'))
    context = _get_default_context(request)
    context.update({'messages':messages,
                    'form': form,
                    'mlist':mlist})
    
    return render_to_response('messaging/mlist_view', context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Example #6
0
    def create(self, request, *args, **kwargs):
        "Send email to some recipients"

        user = request.user.get_profile()

        if request.data is None:
            return rc.BAD_REQUEST

        if request.data.has_key('stream'):
            stream = getOrNone(MessageStream, request.data['stream'])
            if stream and not user.has_permission(stream, mode='x'):
                return rc.FORBIDDEN

        message = Message()
        message.author = user.get_contact()
        if not message.author:
            return rc.FORBIDDEN

        form = MessageForm(user, None, None, request.data, instance=message)
        if form.is_valid():
            message = form.save()
            message.recipients.add(user.get_contact())
            message.set_user_from_request(request)
            message.read_by.add(user)
            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST[
                        'multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module(
                            'treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(
                            pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST['multicomplete_recipients'].split(
                        ',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match(
                                '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+',
                                emailstr):
                            contact, created = Contact.get_or_create_by_email(
                                emailstr, contact_type=default_contact_type)
                            message.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass
            # send email to all recipients
            message.send_email()
            return message
        else:
            self.status = 400
            return form.errors
Example #7
0
    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            self.group, created = Group.objects.get_or_create(name='test')
            duser, created = DjangoUser.objects.get_or_create(
                username=self.username)
            duser.set_password(self.password)
            duser.save()
            self.user, created = User.objects.get_or_create(user=duser)
            self.user.save()
            perspective, created = Perspective.objects.get_or_create(
                name='default')
            perspective.set_default_user()
            perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.message = Message(title='test',
                                   body='test',
                                   author=self.contact,
                                   stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True
Example #8
0
File: views.py Project: 5n1p/treeio
def messaging_compose(request, response_format='html'):
    "New message page"

    user = request.user.get_profile()

    if request.POST:
        if not 'cancel' in request.POST:
            message = Message()
            message.author = user.get_contact()
            if not message.author:
                return user_denied(request,
                                   message="You can't send message without a Contact Card assigned to you.",
                                   response_format=response_format)

            form = MessageForm(
                request.user.get_profile(), None, None, request.POST, instance=message)
            if form.is_valid():
                message = form.save()
                message.recipients.add(user.get_contact())
                message.set_user_from_request(request)
                message.read_by.add(user)
                try:
                    # if email entered create contact and add to recipients
                    if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']:
                        try:
                            conf = ModuleSetting.get_for_module(
                                'treeio.messaging', 'default_contact_type')[0]
                            default_contact_type = ContactType.objects.get(
                                pk=long(conf.value))
                        except Exception:
                            default_contact_type = None
                        emails = request.POST[
                            'multicomplete_recipients'].split(',')
                        for email in emails:
                            emailstr = unicode(email).strip()
                            if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr):
                                contact, created = Contact.get_or_create_by_email(
                                    emailstr, contact_type=default_contact_type)
                                message.recipients.add(contact)
                                if created:
                                    contact.set_user_from_request(request)
                except:
                    pass
                # send email to all recipients
                message.send_email()

                return HttpResponseRedirect(reverse('messaging'))
        else:
            return HttpResponseRedirect(reverse('messaging'))

    else:
        form = MessageForm(request.user.get_profile(), None)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('messaging/message_compose', context,
                              context_instance=RequestContext(request), response_format=response_format)
Example #9
0
    def test_model_message(self):
        "Test message"

        contact_type = ContactType(name='test')
        contact_type.save()

        contact = Contact(name='test', contact_type=contact_type)
        contact.save()

        self.user = DjangoUser(username=self.username, password='')
        self.user.set_password(self.password)
        self.user.save()

        user = User(name='test', user=self.user)
        user.save()

        stream = MessageStream(name='test')
        stream.save()

        obj = Message(title='test', body='test', author=contact, stream=stream)
        obj.save()
        self.assertEquals('test', obj.title)
        self.assertNotEquals(obj.id, None)
        obj.delete()
Example #10
0
    def create(self, request, *args, **kwargs):
        "Send email to some recipients"

        user = request.user.get_profile()

        if request.data is None:
            return rc.BAD_REQUEST

        if request.data.has_key('stream'):
            stream = getOrNone(MessageStream, request.data['stream'])
            if stream and not user.has_permission(stream, mode='x'):
                return rc.FORBIDDEN

        message = Message()
        message.author = user.get_contact()
        if not message.author:
            return rc.FORBIDDEN

        form = MessageForm(user, None, None, request.data, instance=message)
        if form.is_valid():
            message = form.save()
            message.recipients.add(user.get_contact())
            message.set_user_from_request(request)
            message.read_by.add(user)
            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module(
                            'treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(
                            pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST[
                        'multicomplete_recipients'].split(',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr):
                            contact, created = Contact.get_or_create_by_email(
                                emailstr, contact_type=default_contact_type)
                            message.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass
            # send email to all recipients
            message.send_email()
            return message
        else:
            self.status = 400
            return form.errors
Example #11
0
    def test_model_message(self):
        "Test message"

        contact_type = ContactType(name='test')
        contact_type.save()

        contact = Contact(name='test', contact_type=contact_type)
        contact.save()

        self.user = DjangoUser(username=self.username, password='')
        self.user.set_password(self.password)
        self.user.save()

        user = User(name='test', user=self.user)
        user.save()

        stream = MessageStream(name='test')
        stream.save()

        obj = Message(title='test', body='test', author=contact, stream=stream)
        obj.save()
        self.assertEquals('test', obj.title)
        self.assertNotEquals(obj.id, None)
        obj.delete()
Example #12
0
class MessagingViewsTest(TestCase):

    "Messaging functional tests for views"

    username = "******"
    password = "******"
    prepared = False

    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            self.group, created = Group.objects.get_or_create(name='test')
            duser, created = DjangoUser.objects.get_or_create(
                username=self.username)
            duser.set_password(self.password)
            duser.save()
            self.user, created = User.objects.get_or_create(user=duser)
            self.user.save()
            perspective, created = Perspective.objects.get_or_create(
                name='default')
            perspective.set_default_user()
            perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.message = Message(
                title='test', body='test', author=self.contact, stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True

    ######################################
    # Testing views when user is logged in
    ######################################
    def test_message_index_login(self):
        "Test index page with login at /messaging/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging'))
        self.assertEquals(response.status_code, 200)

    def test_message_index_sent(self):
        "Test index page with login at /messaging/sent/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_sent'))
        self.assertEquals(response.status_code, 200)

    def test_message_index_inbox(self):
        "Test index page with login at /messaging/inbox/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_inbox'))
        self.assertEquals(response.status_code, 200)

    def test_message_index_unread(self):
        "Test index page with login at /messaging/unread/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_unread'))
        self.assertEquals(response.status_code, 200)

    # Messages
    def test_message_compose_login(self):
        "Test index page with login at /message/compose/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_message_compose'))
        self.assertEquals(response.status_code, 200)

    def test_message_view_login(self):
        "Test index page with login at /message/view/<message_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_message_view', args=[self.message.id]))
        self.assertEquals(response.status_code, 200)

    def test_message_delete_login(self):
        "Test index page with login at /message/edit/<message_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_message_delete', args=[self.message.id]))
        self.assertEquals(response.status_code, 200)

    # Streams
    def test_stream_add(self):
        "Test index page with login at /stream/add/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    def test_stream_view(self):
        "Test index page with login at /stream/view/<stream_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_view', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    def test_stream_edit(self):
        "Test index page with login at /stream/edit/<stream_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    def test_stream_delete(self):
        "Test index page with login at /stream/delete/<stream_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_delete', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    # Settings
    def test_messaging_settings_view(self):
        "Test index page with login at /messaging/settings/view/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_settings_view'))
        self.assertEquals(response.status_code, 200)

    def test_finance_settings_edit(self):
        "Test index page with login at /messaging/settings/edit/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_settings_edit'))
        self.assertEquals(response.status_code, 200)

    ######################################
    # Testing views when user is not logged in
    ######################################
    def test_message_index_out(self):
        "Test index page at /messaging/"
        response = self.client.get(reverse('messaging'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    def test_message_sent_out(self):
        "Testing /messaging/sent/"
        response = self.client.get(reverse('messaging_sent'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    def test_message_inbox_out(self):
        "Testing /messaging/inbox/"
        response = self.client.get(reverse('messaging_inbox'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    def test_message_unread_out(self):
        "Testing /messaging/unread/"
        response = self.client.get(reverse('messaging_unread'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    # Messages
    def test_message_compose_out(self):
        "Testing /message/compose/"
        response = self.client.get(reverse('messaging_message_compose'))
        self.assertRedirects(response, reverse('user_login'))

    def test_message_view_out(self):
        "Test index page with login at /message/view/<message_id>"
        response = self.client.get(
            reverse('messaging_message_view', args=[self.message.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_message_delete_out(self):
        "Test index page with login at /message/edit/<message_id>"
        response = self.client.get(
            reverse('messaging_message_delete', args=[self.message.id]))
        self.assertRedirects(response, reverse('user_login'))

    # Streams
    def test_stream_add_out(self):
        "Testing /stream/add/"
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_stream_view_out(self):
        "Testing /stream/view/<stream_id>"
        response = self.client.get(
            reverse('messaging_stream_view', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_stream_edit_out(self):
        "Testing /stream/edit/<stream_id>"
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_stream_delete_out(self):
        "Testing /stream/delete/<stream_id>"
        response = self.client.get(
            reverse('messaging_stream_delete', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    # Settings
    def test_messaging_settings_view_out(self):
        "Testing /messaging/settings/view/"
        response = self.client.get(reverse('messaging_settings_view'))
        self.assertRedirects(response, reverse('user_login'))

    def test_finance_settings_edit_out(self):
        "Testing /messaging/settings/edit/"
        response = self.client.get(reverse('messaging_settings_edit'))
        self.assertRedirects(response, reverse('user_login'))
Example #13
0
    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()

            # Create objects

            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.user_contact = Contact(name='test',
                                        related_user=self.user.get_profile(),
                                        contact_type=self.contact_type)
            self.user_contact.set_user(self.user)
            self.user_contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.mlist = MailingList(name='test', from_contact=self.contact)
            self.mlist.set_default_user()
            self.mlist.save()

            self.message = Message(title='test',
                                   body='test',
                                   author=self.contact,
                                   stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True
Example #14
0
class MessagingApiTest(TestCase):

    "Messaging functional tests for api"

    username = "******"
    password = "******"
    prepared = False
    authentication_headers = {
        "CONTENT_TYPE": "application/json",
        "HTTP_AUTHORIZATION": "Basic YXBpX3Rlc3Q6YXBpX3Bhc3N3b3Jk"
    }
    content_type = 'application/json'

    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()

            # Create objects

            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.user_contact = Contact(name='test',
                                        related_user=self.user.get_profile(),
                                        contact_type=self.contact_type)
            self.user_contact.set_user(self.user)
            self.user_contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.mlist = MailingList(name='test', from_contact=self.contact)
            self.mlist.set_default_user()
            self.mlist.save()

            self.message = Message(title='test',
                                   body='test',
                                   author=self.contact,
                                   stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True

    def test_unauthenticated_access(self):
        "Test index page at /api/messaging/mlist"
        response = self.client.get('/api/messaging/mlist')
        # Redirects as unauthenticated
        self.assertEquals(response.status_code, 401)

    def test_get_mlist(self):
        """ Test index page api/messaging/mlist """
        response = self.client.get(path=reverse('api_messaging_mlist'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_one_mlist(self):
        response = self.client.get(path=reverse(
            'api_messaging_mlist', kwargs={'object_ptr': self.mlist.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_mlist(self):
        updates = {
            "name": "API mailing list",
            "description": "API description update",
            "from_contact": self.contact.id,
            "members": [
                self.contact.id,
            ]
        }
        response = self.client.put(path=reverse(
            'api_messaging_mlist', kwargs={'object_ptr': self.mlist.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], updates['name'])
        self.assertEquals(data['description'], updates['description'])
        self.assertEquals(data['from_contact']['id'], updates['from_contact'])
        for i, member in enumerate(data['members']):
            self.assertEquals(member['id'], updates['members'][i])

    def test_get_streams(self):
        """ Test index page api/messaging/streams """
        response = self.client.get(path=reverse('api_messaging_streams'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_stream(self):
        response = self.client.get(path=reverse(
            'api_messaging_streams', kwargs={'object_ptr': self.stream.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_stream(self):
        updates = {
            "name": "API stream",
        }
        response = self.client.put(path=reverse(
            'api_messaging_streams', kwargs={'object_ptr': self.stream.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], updates['name'])

    def test_get_messages(self):
        """ Test index page api/messaging/messages """
        response = self.client.get(path=reverse('api_messaging_messages'),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_message(self):
        response = self.client.get(path=reverse(
            'api_messaging_messages', kwargs={'object_ptr': self.message.id}),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_send_message(self):
        updates = {
            "title": "API message title",
            "body": "Test body",
            "stream": self.stream.id,
            "multicomplete_recipients": u'*****@*****.**'
        }
        response = self.client.post(path=reverse('api_messaging_messages'),
                                    content_type=self.content_type,
                                    data=json.dumps(updates),
                                    **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['title'], updates['title'])
        self.assertEquals(data['body'], updates['body'])
        self.assertEquals(data['stream']['id'], updates['stream'])

    def test_reply_to_message(self):
        updates = {
            "title": "API test",
            "body": "Test body",
            "stream": self.stream.id,
            "multicomplete_recipients": u'*****@*****.**'
        }
        response = self.client.put(path=reverse(
            'api_messaging_messages', kwargs={'object_ptr': self.message.id}),
                                   content_type=self.content_type,
                                   data=json.dumps(updates),
                                   **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertNotEquals(data['title'], updates['title'])
        self.assertEquals(data['body'], updates['body'])
        self.assertEquals(data['stream']['id'], updates['stream'])
Example #15
0
def stream_view(request, stream_id, response_format='html'):
    "Stream view page"

    user = request.user.get_profile()

    stream = get_object_or_404(MessageStream, pk=stream_id)
    if not request.user.get_profile().has_permission(stream):
        return user_denied(request,
                           message="You don't have access to this Stream",
                           response_format=response_format)

    if request.user.get_profile().has_permission(stream, mode='x'):
        if request.POST:
            message = Message()
            message.author = user.get_contact()
            if not message.author:
                return user_denied(
                    request,
                    message=
                    "You can't send message without a Contact Card assigned to you.",
                    response_format=response_format)

            form = MessageForm(request.user.get_profile(),
                               None,
                               None,
                               request.POST,
                               instance=message)
            if form.is_valid():
                message = form.save()
                message.recipients.add(user.get_contact())
                message.set_user_from_request(request)
                message.read_by.add(user)
                try:
                    # if email entered create contact and add to recipients
                    if 'multicomplete_recipients' in request.POST and request.POST[
                            'multicomplete_recipients']:
                        try:
                            conf = ModuleSetting.get_for_module(
                                'treeio.messaging', 'default_contact_type')[0]
                            default_contact_type = ContactType.objects.get(
                                pk=long(conf.value))
                        except Exception:
                            default_contact_type = None
                        emails = request.POST[
                            'multicomplete_recipients'].split(',')
                        for email in emails:
                            emailstr = unicode(email).strip()
                            if re.match(
                                    '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+',
                                    emailstr):
                                contact, created = Contact.get_or_create_by_email(
                                    emailstr,
                                    contact_type=default_contact_type)
                                message.recipients.add(contact)
                                if created:
                                    contact.set_user_from_request(request)
                except:
                    pass
                # send email to all recipients
                message.send_email()

                return HttpResponseRedirect(
                    reverse('messaging_stream_view', args=[stream.id]))
        else:
            form = MessageForm(request.user.get_profile(), stream_id)

    else:
        form = None

    objects = Object.filter_by_request(
        request,
        Message.objects.filter(reply_to__isnull=True,
                               stream=stream).order_by('-date_created'))
    context = _get_default_context(request)
    context.update({'messages': objects, 'form': form, 'stream': stream})

    return render_to_response('messaging/stream_view',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Example #16
0
def messaging_view(request, message_id, response_format='html'):
    "Single message page"
    
    message = get_object_or_404(Message, pk=message_id)
    user = request.user.get_profile()

    if not user.has_permission(message):
        return user_denied(request, message="You don't have access to this Message", 
                           response_format=response_format)

    message.read_by.add(user)

    if request.POST and request.POST.get('body', False):
        "Unread message"
        
        reply = Message()
        reply.author = user.get_contact()
        if not reply.author:
            return user_denied(request, 
                               message="You can't send message without a Contact Card assigned to you.", 
                               response_format=response_format)
        reply.reply_to = message
        form = MessageReplyForm(user, message.stream_id, message, request.POST, instance=reply)
        if form.is_valid():
            reply = form.save()
            reply.set_user_from_request(request)
            # Add author to recipients
            reply.recipients.add(reply.author)
            message.read_by.clear()
            
            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module('treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST['multicomplete_recipients'].split(',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr):
                            contact, created = Contact.get_or_create_by_email(emailstr, contact_type=default_contact_type)
                            reply.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass
            
            # Add each recipient of the reply to the original message
            for recipient in reply.recipients.all():
                message.recipients.add(recipient)
            
            # send email to all recipients
            reply.send_email()
            
            return HttpResponseRedirect(reverse('messaging_message_view', args=[message.id]))
        
    else:   
        form = MessageReplyForm(request.user.get_profile(), message.stream_id, message)
    
    replies = Object.filter_by_request(request, 
                                       Message.objects.filter(reply_to=message).order_by('date_created'))
    
    context = _get_default_context(request)
    context.update({'message':message,
                    'messages':replies,
                    'form':form})

    return render_to_response('messaging/message_view', context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Example #17
0
def stream_view(request, stream_id, response_format='html'):
    "Stream view page"
    
    user = request.user.get_profile()
    
    stream = get_object_or_404(MessageStream, pk=stream_id)
    if not request.user.get_profile().has_permission(stream):
        return user_denied(request, message="You don't have access to this Stream", 
                           response_format=response_format)
        
    if request.user.get_profile().has_permission(stream, mode='x'):
        if request.POST:
            message = Message()
            message.author = user.get_contact()
            if not message.author:
                return user_denied(request, 
                                   message="You can't send message without a Contact Card assigned to you.", 
                                   response_format=response_format)
    
            form = MessageForm(request.user.get_profile(), None, None, request.POST, instance=message)
            if form.is_valid():
                message = form.save()
                message.recipients.add(user.get_contact())
                message.set_user_from_request(request)
                message.read_by.add(user)
                try:
                    # if email entered create contact and add to recipients
                    if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']:
                        try:
                            conf = ModuleSetting.get_for_module('treeio.messaging', 'default_contact_type')[0]
                            default_contact_type = ContactType.objects.get(pk=long(conf.value))
                        except Exception:
                            default_contact_type = None
                        emails = request.POST['multicomplete_recipients'].split(',')
                        for email in emails:
                            emailstr = unicode(email).strip()
                            if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr):
                                contact, created = Contact.get_or_create_by_email(emailstr, contact_type=default_contact_type)
                                message.recipients.add(contact)
                                if created:
                                    contact.set_user_from_request(request)
                except:
                    pass
                # send email to all recipients
                message.send_email()
                
                return HttpResponseRedirect(reverse('messaging_stream_view', args=[stream.id]))
        else:   
            form = MessageForm(request.user.get_profile(), stream_id)

    else:
        form = None
        
    messages = Object.filter_by_request(request, 
                                        Message.objects.filter(reply_to__isnull=True, 
                                                               stream=stream).order_by('-date_created'))
    context = _get_default_context(request)
    context.update({'messages':messages,
                    'form': form,
                    'stream':stream})
    
    return render_to_response('messaging/stream_view', context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Example #18
0
    def process_msg(self, msg, attrs, attachments):
        "Save message, Cap!"
        from treeio.messaging.models import Message

        try:
            conf = ModuleSetting.get_for_module("treeio.messaging", "default_contact_type")[0]
            default_contact_type = ContactType.objects.get(pk=long(conf.value))
        except:
            default_contact_type = None

        email_author, created = Contact.get_or_create_by_email(
            attrs.author_email, attrs.author_name, default_contact_type
        )
        if created:
            email_author.copy_permissions(self.stream)

        # check if the message is already retrieved
        threshold = datetime.datetime.now() - datetime.timedelta(minutes=20)
        existing = Message.objects.filter(
            stream=self.stream, title=attrs.subject, author=email_author, date_created__gte=threshold
        ).exists()
        if not existing:
            # check if it could be a renamed ticket message
            existing = Message.objects.filter(
                stream=self.stream,
                title__regex=r"\[#\d*\] %s" % attrs.subject,
                author=email_author,
                date_created__gte=threshold,
            ).exists()
        if not existing:
            message = None
            if attrs.subject[:3] in MAIL_PREF:
                if attrs.subject[3] == " ":
                    original_subject = attrs.subject[4:]
                else:
                    original_subject = attrs.subject[3:]

                try:
                    query = (
                        Q(reply_to__isnull=True)
                        & Q(recipients=email_author)
                        & (Q(title=original_subject) | Q(title=attrs.subject))
                    )
                    original = Message.objects.filter(query).order_by("-date_created")[:1][0]
                    message = Message(
                        title=attrs.subject, body=attrs.body, author=email_author, stream=self.stream, reply_to=original
                    )
                    message.date_created = datetime.datetime.now()

                    message.is_mail = True
                    message.save()
                    message.copy_permissions(original)
                    original.read_by.clear()
                except IndexError:
                    pass
            if not message:
                message = Message(title=attrs.subject, body=attrs.body, author=email_author, stream=self.stream)
                message.date_created = datetime.datetime.now()
                message.is_mail = True
                message.save()
                message.copy_permissions(self.stream)
                message.recipients.add(email_author)
Example #19
0
    def update(self, request, *args, **kwargs):
        "Reply to message"

        if request.data is None:
            return rc.BAD_REQUEST

        pkfield = kwargs.get(self.model._meta.pk.name) or request.data.get(
            self.model._meta.pk.name)

        if not pkfield:
            return rc.BAD_REQUEST

        user = request.user.get_profile()

        try:
            message = self.model.objects.get(pk=pkfield)
        except ObjectDoesNotExist:
            return rc.NOT_FOUND

        if not user.has_permission(message):
            return rc.FORBIDDEN

        reply = Message()
        reply.author = user.get_contact()
        if not reply.author:
            return rc.FORBIDDEN

        reply.reply_to = message
        form = MessageReplyForm(
            user, message.stream_id, message, request.data, instance=reply)
        if form.is_valid():
            reply = form.save()
            reply.set_user_from_request(request)
            # Add author to recipients
            reply.recipients.add(reply.author)
            message.read_by.clear()

            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module(
                            'treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(
                            pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST[
                        'multicomplete_recipients'].split(',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr):
                            contact, created = Contact.get_or_create_by_email(
                                emailstr, contact_type=default_contact_type)
                            reply.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass

            # Add each recipient of the reply to the original message
            for recipient in reply.recipients.all():
                message.recipients.add(recipient)

            # send email to all recipients
            reply.send_email()
            return reply

        else:
            self.status = 400
            return form.errors
Example #20
0
class MessagingViewsTest(TestCase):

    "Messaging functional tests for views"

    username = "******"
    password = "******"
    prepared = False

    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            self.group, created = Group.objects.get_or_create(name='test')
            duser, created = DjangoUser.objects.get_or_create(
                username=self.username)
            duser.set_password(self.password)
            duser.save()
            self.user, created = User.objects.get_or_create(user=duser)
            self.user.save()
            perspective, created = Perspective.objects.get_or_create(
                name='default')
            perspective.set_default_user()
            perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.message = Message(
                title='test', body='test', author=self.contact, stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True

    ######################################
    # Testing views when user is logged in
    ######################################
    def test_message_index_login(self):
        "Test index page with login at /messaging/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging'))
        self.assertEquals(response.status_code, 200)

    def test_message_index_sent(self):
        "Test index page with login at /messaging/sent/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_sent'))
        self.assertEquals(response.status_code, 200)

    def test_message_index_inbox(self):
        "Test index page with login at /messaging/inbox/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_inbox'))
        self.assertEquals(response.status_code, 200)

    def test_message_index_unread(self):
        "Test index page with login at /messaging/unread/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_unread'))
        self.assertEquals(response.status_code, 200)

    # Messages
    def test_message_compose_login(self):
        "Test index page with login at /message/compose/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_message_compose'))
        self.assertEquals(response.status_code, 200)

    def test_message_view_login(self):
        "Test index page with login at /message/view/<message_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_message_view', args=[self.message.id]))
        self.assertEquals(response.status_code, 200)

    def test_message_delete_login(self):
        "Test index page with login at /message/edit/<message_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_message_delete', args=[self.message.id]))
        self.assertEquals(response.status_code, 200)

    # Streams
    def test_stream_add(self):
        "Test index page with login at /stream/add/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    def test_stream_view(self):
        "Test index page with login at /stream/view/<stream_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_view', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    def test_stream_edit(self):
        "Test index page with login at /stream/edit/<stream_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    def test_stream_delete(self):
        "Test index page with login at /stream/delete/<stream_id>"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(
            reverse('messaging_stream_delete', args=[self.stream.id]))
        self.assertEquals(response.status_code, 200)

    # Settings
    def test_messaging_settings_view(self):
        "Test index page with login at /messaging/settings/view/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_settings_view'))
        self.assertEquals(response.status_code, 200)

    def test_finance_settings_edit(self):
        "Test index page with login at /messaging/settings/edit/"
        response = self.client.post('/accounts/login',
                                    {'username': self.username, 'password': self.password})
        self.assertRedirects(response, '/')
        response = self.client.get(reverse('messaging_settings_edit'))
        self.assertEquals(response.status_code, 200)

    ######################################
    # Testing views when user is not logged in
    ######################################
    def test_message_index_out(self):
        "Test index page at /messaging/"
        response = self.client.get(reverse('messaging'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    def test_message_sent_out(self):
        "Testing /messaging/sent/"
        response = self.client.get(reverse('messaging_sent'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    def test_message_inbox_out(self):
        "Testing /messaging/inbox/"
        response = self.client.get(reverse('messaging_inbox'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    def test_message_unread_out(self):
        "Testing /messaging/unread/"
        response = self.client.get(reverse('messaging_unread'))
        # Redirects as unauthenticated
        self.assertRedirects(response, reverse('user_login'))

    # Messages
    def test_message_compose_out(self):
        "Testing /message/compose/"
        response = self.client.get(reverse('messaging_message_compose'))
        self.assertRedirects(response, reverse('user_login'))

    def test_message_view_out(self):
        "Test index page with login at /message/view/<message_id>"
        response = self.client.get(
            reverse('messaging_message_view', args=[self.message.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_message_delete_out(self):
        "Test index page with login at /message/edit/<message_id>"
        response = self.client.get(
            reverse('messaging_message_delete', args=[self.message.id]))
        self.assertRedirects(response, reverse('user_login'))

    # Streams
    def test_stream_add_out(self):
        "Testing /stream/add/"
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_stream_view_out(self):
        "Testing /stream/view/<stream_id>"
        response = self.client.get(
            reverse('messaging_stream_view', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_stream_edit_out(self):
        "Testing /stream/edit/<stream_id>"
        response = self.client.get(
            reverse('messaging_stream_edit', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    def test_stream_delete_out(self):
        "Testing /stream/delete/<stream_id>"
        response = self.client.get(
            reverse('messaging_stream_delete', args=[self.stream.id]))
        self.assertRedirects(response, reverse('user_login'))

    # Settings
    def test_messaging_settings_view_out(self):
        "Testing /messaging/settings/view/"
        response = self.client.get(reverse('messaging_settings_view'))
        self.assertRedirects(response, reverse('user_login'))

    def test_finance_settings_edit_out(self):
        "Testing /messaging/settings/edit/"
        response = self.client.get(reverse('messaging_settings_edit'))
        self.assertRedirects(response, reverse('user_login'))
Example #21
0
def messaging_compose(request, response_format='html'):
    "New message page"

    user = request.user.get_profile()

    if request.POST:
        if not 'cancel' in request.POST:
            message = Message()
            message.author = user.get_contact()
            if not message.author:
                return user_denied(
                    request,
                    message=
                    "You can't send message without a Contact Card assigned to you.",
                    response_format=response_format)

            form = MessageForm(request.user.get_profile(),
                               None,
                               None,
                               request.POST,
                               instance=message)
            if form.is_valid():
                message = form.save()
                message.recipients.add(user.get_contact())
                message.set_user_from_request(request)
                message.read_by.add(user)
                try:
                    # if email entered create contact and add to recipients
                    if 'multicomplete_recipients' in request.POST and request.POST[
                            'multicomplete_recipients']:
                        try:
                            conf = ModuleSetting.get_for_module(
                                'treeio.messaging', 'default_contact_type')[0]
                            default_contact_type = ContactType.objects.get(
                                pk=long(conf.value))
                        except Exception:
                            default_contact_type = None
                        emails = request.POST[
                            'multicomplete_recipients'].split(',')
                        for email in emails:
                            emailstr = unicode(email).strip()
                            if re.match(
                                    '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+',
                                    emailstr):
                                contact, created = Contact.get_or_create_by_email(
                                    emailstr,
                                    contact_type=default_contact_type)
                                message.recipients.add(contact)
                                if created:
                                    contact.set_user_from_request(request)
                except:
                    pass
                # send email to all recipients
                message.send_email()

                return HttpResponseRedirect(reverse('messaging'))
        else:
            return HttpResponseRedirect(reverse('messaging'))

    else:
        form = MessageForm(request.user.get_profile(), None)

    context = _get_default_context(request)
    context.update({'form': form})

    return render_to_response('messaging/message_compose',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)
Example #22
0
    def update(self, request, *args, **kwargs):
        "Reply to message"

        if request.data is None:
            return rc.BAD_REQUEST

        pkfield = kwargs.get(self.model._meta.pk.name) or request.data.get(
            self.model._meta.pk.name)

        if not pkfield:
            return rc.BAD_REQUEST

        user = request.user.get_profile()

        try:
            message = self.model.objects.get(pk=pkfield)
        except ObjectDoesNotExist:
            return rc.NOT_FOUND

        if not user.has_permission(message):
            return rc.FORBIDDEN

        reply = Message()
        reply.author = user.get_contact()
        if not reply.author:
            return rc.FORBIDDEN

        reply.reply_to = message
        form = MessageReplyForm(user,
                                message.stream_id,
                                message,
                                request.data,
                                instance=reply)
        if form.is_valid():
            reply = form.save()
            reply.set_user_from_request(request)
            # Add author to recipients
            reply.recipients.add(reply.author)
            message.read_by.clear()

            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST[
                        'multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module(
                            'treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(
                            pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST['multicomplete_recipients'].split(
                        ',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match(
                                '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+',
                                emailstr):
                            contact, created = Contact.get_or_create_by_email(
                                emailstr, contact_type=default_contact_type)
                            reply.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass

            # Add each recipient of the reply to the original message
            for recipient in reply.recipients.all():
                message.recipients.add(recipient)

            # send email to all recipients
            reply.send_email()
            return reply

        else:
            self.status = 400
            return form.errors
Example #23
0
class MessagingApiTest(TestCase):
    "Messaging functional tests for api"

    username = "******"
    password = "******"
    prepared = False
    authentication_headers ={"CONTENT_TYPE": "application/json",
                             "HTTP_AUTHORIZATION" : "Basic YXBpX3Rlc3Q6YXBpX3Bhc3N3b3Jk" }
    content_type ='application/json'

    def setUp(self):
        "Initial Setup"

        if not self.prepared:
            # Clean up first
            Object.objects.all().delete()

            # Create objects

            try:
                self.group = Group.objects.get(name='test')
            except Group.DoesNotExist:
                Group.objects.all().delete()
                self.group = Group(name='test')
                self.group.save()

            try:
                self.user = DjangoUser.objects.get(username=self.username)
                self.user.set_password(self.password)
                try:
                    self.profile = self.user.get_profile()
                except Exception:
                    User.objects.all().delete()
                    self.user = DjangoUser(username=self.username, password='')
                    self.user.set_password(self.password)
                    self.user.save()
            except DjangoUser.DoesNotExist:
                User.objects.all().delete()
                self.user = DjangoUser(username=self.username, password='')
                self.user.set_password(self.password)
                self.user.save()

            try:
                perspective = Perspective.objects.get(name='default')
            except Perspective.DoesNotExist:
                Perspective.objects.all().delete()
                perspective = Perspective(name='default')
                perspective.set_default_user()
                perspective.save()
            ModuleSetting.set('default_perspective', perspective.id)

            self.contact_type = ContactType(name='test')
            self.contact_type.set_default_user()
            self.contact_type.save()

            self.contact = Contact(name='test', contact_type=self.contact_type)
            self.contact.set_default_user()
            self.contact.save()

            self.user_contact = Contact(name='test', related_user=self.user.get_profile(), contact_type=self.contact_type)
            self.user_contact.set_user(self.user)
            self.user_contact.save()

            self.stream = MessageStream(name='test')
            self.stream.set_default_user()
            self.stream.save()

            self.mlist = MailingList(name='test', from_contact=self.contact)
            self.mlist.set_default_user()
            self.mlist.save()

            self.message = Message(title='test', body='test', author=self.contact, stream=self.stream)
            self.message.set_default_user()
            self.message.save()

            self.client = Client()

            self.prepared = True

    def test_unauthenticated_access(self):
        "Test index page at /api/messaging/mlist"
        response = self.client.get('/api/messaging/mlist')
        # Redirects as unauthenticated
        self.assertEquals(response.status_code, 401)

    def test_get_mlist(self):
        """ Test index page api/messaging/mlist """
        response = self.client.get(path=reverse('api_messaging_mlist'), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_one_mlist(self):
        response = self.client.get(path=reverse('api_messaging_mlist', kwargs={'object_ptr': self.mlist.id}), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_mlist(self):
        updates = {"name": "API mailing list", "description": "API description update", "from_contact": self.contact.id,
                   "members": [self.contact.id,]}
        response = self.client.put(path=reverse('api_messaging_mlist', kwargs={'object_ptr': self.mlist.id}),
                                   content_type=self.content_type,  data=json.dumps(updates), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], updates['name'])
        self.assertEquals(data['description'], updates['description'])
        self.assertEquals(data['from_contact']['id'], updates['from_contact'])
        for i, member in enumerate(data['members']):
            self.assertEquals(member['id'], updates['members'][i])

    def test_get_streams(self):
        """ Test index page api/messaging/streams """
        response = self.client.get(path=reverse('api_messaging_streams'), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_stream(self):
        response = self.client.get(path=reverse('api_messaging_streams', kwargs={'object_ptr': self.stream.id}), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_update_stream(self):
        updates = {"name": "API stream", }
        response = self.client.put(path=reverse('api_messaging_streams', kwargs={'object_ptr': self.stream.id}),
                                   content_type=self.content_type,  data=json.dumps(updates), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['name'], updates['name'])

    def test_get_messages(self):
        """ Test index page api/messaging/messages """
        response = self.client.get(path=reverse('api_messaging_messages'), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_get_message(self):
        response = self.client.get(path=reverse('api_messaging_messages', kwargs={'object_ptr': self.message.id}), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

    def test_send_message(self):
        updates = {"title": "API message title", "body": "Test body", "stream": self.stream.id,
                   "multicomplete_recipients": u'*****@*****.**'}
        response = self.client.post(path=reverse('api_messaging_messages'), content_type=self.content_type,
                                    data=json.dumps(updates), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertEquals(data['title'], updates['title'])
        self.assertEquals(data['body'], updates['body'])
        self.assertEquals(data['stream']['id'], updates['stream'])

    def test_reply_to_message(self):
        updates = {"title": "API test", "body": "Test body", "stream": self.stream.id,
                   "multicomplete_recipients": u'*****@*****.**'}
        response = self.client.put(path=reverse('api_messaging_messages', kwargs={'object_ptr': self.message.id}),
                                   content_type=self.content_type,  data=json.dumps(updates), **self.authentication_headers)
        self.assertEquals(response.status_code, 200)

        data = json.loads(response.content)
        self.assertNotEquals(data['title'], updates['title'])
        self.assertEquals(data['body'], updates['body'])
        self.assertEquals(data['stream']['id'], updates['stream'])
Example #24
0
    def save(self, *args, **kwargs):
        "Set Resolution if selected"
        instance = super(TicketRecordForm, self).save(*args, **kwargs)
        ticket = self.ticket
        if 'resolution' in self.cleaned_data and self.cleaned_data[
                'resolution']:
            ticket.resolution = self.cleaned_data['body']
            ticket.save()

        # Send update if notify clicked
        if 'notify' in self.cleaned_data and self.cleaned_data[
                'notify'] and ticket.caller:
            toaddr = ticket.caller.get_email()
            if ticket.message or toaddr:
                reply = Message()
                reply.author = instance.sender
                reply.body = instance.body
                reply.auto_notify = False
                if ticket.message:
                    reply.stream = ticket.message.stream
                    reply.reply_to = ticket.message
                else:
                    reply.stream = ticket.queue.message_stream if ticket.queue else None
                    reply.title = "[#%s] %s" % (ticket.reference, ticket.name)
                reply.save()
                if not ticket.message:
                    ticket.message = reply
                reply.recipients.add(ticket.caller)
                email = EmailMessage(reply)
                email.send_email()

        return instance
Example #25
0
    def process_msg(self, msg, attrs, attachments):
        "Save message, Cap!"
        from treeio.messaging.models import Message

        try:
            conf = ModuleSetting.get_for_module(
                'treeio.messaging', 'default_contact_type')[0]
            default_contact_type = ContactType.objects.get(pk=long(conf.value))
        except:
            default_contact_type = None

        email_author, created = Contact.get_or_create_by_email(
            attrs.author_email, attrs.author_name, default_contact_type)
        if created:
            email_author.copy_permissions(self.stream)

        # check if the message is already retrieved
        existing = Message.objects.filter(
            stream=self.stream, title=attrs.subject, author=email_author, body=attrs.body).exists()
        if not existing:
            message = None
            if attrs.subject[:3] == 'Re:':
                # process replies
                if attrs.subject[:4] == 'Re: ':
                    original_subject = attrs.subject[4:]
                else:
                    original_subject = attrs.subject[3:]

                try:
                    query = Q(reply_to__isnull=True) & Q(recipients=email_author) & (
                        Q(title=original_subject) | Q(title=attrs.subject))
                    original = Message.objects.filter(
                        query).order_by('-date_created')[:1][0]
                    message = Message(title=attrs.subject, body=attrs.body, author=email_author,
                                      stream=self.stream, reply_to=original)
                    if attrs.email_date:
                        message.date_created = attrs.email_date

                    message.save()
                    message.copy_permissions(original)
                    original.read_by.clear()
                except IndexError:
                    pass
            if not message:
                message = Message(
                    title=attrs.subject, body=attrs.body, author=email_author, stream=self.stream)
                if attrs.email_date:
                    message.date_created = attrs.email_date
                message.save()
                message.copy_permissions(self.stream)
                message.recipients.add(email_author)
Example #26
0
def messaging_view(request, message_id, response_format='html'):
    "Single message page"

    message = get_object_or_404(Message, pk=message_id)
    user = request.user.get_profile()

    if not user.has_permission(message):
        return user_denied(request,
                           message="You don't have access to this Message",
                           response_format=response_format)

    message.read_by.add(user)

    if request.POST and request.POST.get('body', False):
        "Unread message"

        reply = Message()
        reply.author = user.get_contact()
        if not reply.author:
            return user_denied(
                request,
                message=
                "You can't send message without a Contact Card assigned to you.",
                response_format=response_format)
        reply.reply_to = message
        form = MessageReplyForm(user,
                                message.stream_id,
                                message,
                                request.POST,
                                instance=reply)
        if form.is_valid():
            reply = form.save()
            reply.set_user_from_request(request)
            # Add author to recipients
            reply.recipients.add(reply.author)
            message.read_by.clear()

            try:
                # if email entered create contact and add to recipients
                if 'multicomplete_recipients' in request.POST and request.POST[
                        'multicomplete_recipients']:
                    try:
                        conf = ModuleSetting.get_for_module(
                            'treeio.messaging', 'default_contact_type')[0]
                        default_contact_type = ContactType.objects.get(
                            pk=long(conf.value))
                    except Exception:
                        default_contact_type = None
                    emails = request.POST['multicomplete_recipients'].split(
                        ',')
                    for email in emails:
                        emailstr = unicode(email).strip()
                        if re.match(
                                '[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+',
                                emailstr):
                            contact, created = Contact.get_or_create_by_email(
                                emailstr, contact_type=default_contact_type)
                            reply.recipients.add(contact)
                            if created:
                                contact.set_user_from_request(request)
            except:
                pass

            # Add each recipient of the reply to the original message
            for recipient in reply.recipients.all():
                message.recipients.add(recipient)

            # send email to all recipients
            reply.send_email()

            return HttpResponseRedirect(
                reverse('messaging_message_view', args=[message.id]))

    else:
        form = MessageReplyForm(request.user.get_profile(), message.stream_id,
                                message)

    replies = Object.filter_by_request(
        request,
        Message.objects.filter(reply_to=message).order_by('date_created'))

    context = _get_default_context(request)
    context.update({'message': message, 'messages': replies, 'form': form})

    return render_to_response('messaging/message_view',
                              context,
                              context_instance=RequestContext(request),
                              response_format=response_format)