Beispiel #1
0
def create_user_mboxes(context):
    site = find_site(context)
    mboxes = site['mailboxes']
    for mbox_suffix in 'inbox', 'sent':
        mbox_name = context.__name__ + '.' + mbox_suffix
    
        mbt = MailboxTool()
        mbt.get_mailbox(mboxes, mbox_name)
Beispiel #2
0
def delete_thread(context, request):

    user = authenticated_userid(request)

    success = False
    error_msg = ''

    thread_id = request.params.get('thread_id', '')
    mbox_type = _get_mbox_type(request)

    mbt = MailboxTool()

    try:
        mbt.delete_thread(context, user, mbox_type, thread_id)
    except Exception, e:
        error_msg = format_exc(e)
Beispiel #3
0
 def setUp(self):
     self.mbt = MailboxTool()
     self.log = LogCapture()
     self.context = DummyModel()
     self.context['mailboxes'] = DummyModel()
     self.context.users = DummyUsers()
     self.bob = DummyProfile()
     self.bob.__name__ = 'bob'
     self.alice = DummyProfile()
     self.alice.__name__ = 'alice'
Beispiel #4
0
def mark_message_read(context, request):

    user = authenticated_userid(request)

    success = False
    error_msg = ''

    thread_id = request.params.get('thread_id', '')
    message_id = request.params.get('message_id', '')
    mbox_type = _get_mbox_type(request)

    mbt = MailboxTool()

    try:
        raw_msg, msg = mbt.get_message(context, user, mbox_type, thread_id, message_id)
        if not STATUS_READ in raw_msg.flags:
            raw_msg.flags.append(STATUS_READ)
    except Exception, e:
        error_msg = format_exc(e)
Beispiel #5
0
def send_to(context, request, to, people_list, store_sent=False, thread_id=None):
    user = authenticated_userid(request)

    now = str(datetime.utcnow())
    is_reply = False
    if request.POST.get('thread_id'):
        is_reply = True

    subject = request.POST.get('subject') or '(empty subject)'
    payload = request.POST.get('payload', '')
    if thread_id is None:
        # We don't have a thread id. We try to get it from a post variable
        # (reply) or we create it (new thread).
        thread_id = request.POST.get('thread_id') 
        if thread_id is None:
            thread_id = MailboxTool.new_thread_id()

    mbt = MailboxTool()

#   FIXME not sure if this is actually used
#    unread = mbt.get_unread(context, user, 'inbox')
#    return_data['unread'] = unread

    msg = MboxMessage(payload.encode('utf-8'))
    msg['Message-Id'] = MailboxTool.new_message_id()
    if not is_reply:
        msg['Subject'] = subject
        # We'll setup the subject automatically if it's a reply
    msg['From'] = user
    msg['To'] = to
    msg['Date'] = now
    msg['X-oc-thread-id'] = thread_id
    msg['X-people-list'] = ','.join(people_list)

    site = find_site(context)
    to_profile = request.api.find_profile(to)
    from_profile = request.api.find_profile(user)
    if is_reply:
        mbt.send_reply(site, thread_id, user, to_profile, msg,
                store_sent=store_sent)
    else:
        mbt.send_message(site, user, to_profile, msg,
                store_sent=store_sent)

    eventinfo = _MBoxEvent()
    eventinfo['content'] = msg
    eventinfo['content_type'] = 'MBoxMessage'
    eventinfo['context_url'] = from_profile.__name__

    eventinfo.mfrom = from_profile.__name__
    eventinfo.mfrom_name = from_profile.__name__
    eventinfo.mto = [to_profile.email]
    eventinfo.message = msg

    alert_user(to_profile, eventinfo)

    return thread_id
Beispiel #6
0
class MBoxViewTestCase(unittest.TestCase):

    def setUp(self):
        self.mbt = MailboxTool()
        self.log = LogCapture()
        self.context = DummyModel()
        self.context['mailboxes'] = DummyModel()
        self.context.users = DummyUsers()
        self.bob = DummyProfile()
        self.bob.__name__ = 'bob'
        self.alice = DummyProfile()
        self.alice.__name__ = 'alice'

    def tearDown(self):
        cleanUp()

    def _get_mbox_request(self, mbox_type, key='mbox_type'):
        request = DummyRequest()
        request.params[key] =  mbox_type

        return request

    def test_per_page(self):
        self.assertEquals(PER_PAGE, 20)

    def test_json_response(self):
        success = uuid.uuid4().hex
        error_msg = uuid.uuid4().hex

        response = _json_response(success, error_msg)

        self.assertTrue(isinstance(response, Response))
        self.assertEquals(response.content_type, 'application/x-json')

        given_body = sorted(JSONDecoder().decode(response.body).items())
        expected_body = [('error_msg', error_msg), ('success', success)]
        self.assertEquals(given_body, expected_body)

    def test_get_mbox_type(self):
        mbox_type = _get_mbox_type(self._get_mbox_request('inbox'))
        self.assertEquals(mbox_type, 'inbox')

        mbox_type = _get_mbox_type(self._get_mbox_request('sent'))
        self.assertEquals(mbox_type, 'sent')

        # Unrecognized mbox type, should revert to default inbox.
        mbox_type = _get_mbox_type(self._get_mbox_request(uuid.uuid4().hex))
        self.assertEquals(mbox_type, DEFAULT_MBOX_TYPE)

        # Unrecognized key, should revert to default inbox.
        mbox_type = _get_mbox_type(self._get_mbox_request('inbox', key=uuid.uuid4().hex))
        self.assertEquals(mbox_type, DEFAULT_MBOX_TYPE)


    def test_show_mbox(self):

        _people_url = uuid.uuid4().hex
        _firstname = uuid.uuid4().hex
        _lastname = uuid.uuid4().hex
        _country = uuid.uuid4().hex

        class _DummyAPI(object):

            static_url = '/foo/bar'

            def find_profile(*ignored_args, **ignored_kwargs):
                class _Dummy(object):
                    firstname = _firstname
                    lastname = _lastname
                    country = _country
                    organization = uuid.uuid4().hex
                    thumb_url = lambda _profile, _request: '/test-thumb.jpg'

                return _Dummy()

            people_url = _people_url

        with Replacer() as r:
            r.replace('opencore.views.mbox.authenticated_userid', _authenticated_user_id)
            r.replace('opencore.views.mbox._get_profile_details',
                    lambda context, request, user: {})


            site, from_, _, msg, thread_id, _, _, _, payload, _ = get_data()
            to = find_profiles(site)['admin']
            self.mbt.send_message(site, from_, to, msg, should_commit=True)

            site, _ = open_root(get_default_config())
            request = DummyRequest()
            request.params['thread_id'] = thread_id
            request.api = _DummyAPI()

            response = show_mbox_thread(site, request)

            self.assertTrue(isinstance(response['api'], _DummyAPI))

            self.assertTrue(len(response['messages']), 1)
            message = response['messages'][0]

            flags = message['flags']
            if flags:
                self.assertEquals(flags, ['READ'])

            self.assertEquals(message['from'], 'admin')
            self.assertEquals(message['from_country'], _country)
            self.assertEquals(message['from_firstname'], _firstname)
            self.assertEquals(message['from_lastname'], _lastname)
            self.assertEquals(message['from_photo'], '/test-thumb.jpg')
            self.assertEquals(message['payload'], payload)
            self.assertTrue(len(message['payload']) > 20)
            self.assertTrue(len(message['queue_id']) > 20)

            self.assertTrue(len(message['to_data']) == 2)
            to_data = message['to_data']

            for to_datum in to_data:
                self.assertEquals(to_datum['country'], _country)
                self.assertEquals(to_datum['firstname'], _firstname)
                self.assertEquals(to_datum['lastname'], _lastname)

                name = to_datum['name']
                self.assertTrue(name in ('joe', 'sarah'))
                self.assertEquals(to_datum['photo_url'], '/test-thumb.jpg')

    def test_add_message(self):

        subject = uuid.uuid4().hex
        payload = uuid.uuid4().hex

        site, _ = open_root(get_default_config())
        to = find_profiles(site)['sarah']

        with Replacer() as r:
            r.replace('opencore.views.mbox.authenticated_userid', _authenticated_user_id)
            r.replace('opencore.views.mbox._get_profile_details',
                    lambda context, request, user: {})

            request = DummyRequest(method='POST')
            request.api = DummyAPI()
            request.api.find_profile = (lambda userid: 
                    self.bob if userid == 'bob' else self.alice)
            request.POST = MultiDict([
                ('to[]', 'bob'),
                ('subject', subject),
                ('payload', payload),
                ])

            response = add_message(site, request)
            self.assertTrue("mbox_thread" in response.location)

            transaction.commit()

    def test_add_message_multiple_recipients(self):
        subject = uuid.uuid4().hex
        payload = uuid.uuid4().hex

        with Replacer() as r:
            r.replace('opencore.views.mbox.authenticated_userid', _authenticated_user_id)
            r.replace('opencore.views.mbox._get_profile_details',
                    lambda context, request, user: {})

            request = DummyRequest(method='POST')
            request.POST = MultiDict([
                ('to[]', 'bob'),
                ('to[]', 'alice'),
                ('subject', subject),
                ('payload', payload),
                ])
            request.api = DummyAPI()
            request.api.find_profile = (lambda userid: 
                    self.bob if userid == 'bob' else self.alice)

            response = add_message(self.context, request)

            # Mailboxes have been created
            self.assertTrue('bob.inbox' in self.context['mailboxes'])
            self.assertTrue('alice.inbox' in self.context['mailboxes'])

            # Queues have been created
            bob_inbox = self.context['mailboxes']['bob.inbox']
            alice_inbox = self.context['mailboxes']['alice.inbox']
            self.assertEquals(len(bob_inbox), 1)
            self.assertEquals(len(alice_inbox), 1)

            # Redirect to new message
            self.assertEquals(
                   'http://example.com/mbox_thread.html?' 
                   + urlencode({'thread_id': alice_inbox[0].id})
                   + '#last-message',
                   response.location)
            r.restore()

            transaction.commit()

    def test_delete_message(self):

        api = uuid.uuid4().hex

        with Replacer() as r:
            r.replace('opencore.views.mbox.authenticated_userid', _authenticated_user_id)

            site, from_, _, msg, thread_id, msg_id, _, _, _, _ = get_data()
            to = find_profiles(site)['admin']
            self.mbt.send_message(site, from_, to, msg, should_commit=True)

            request = DummyRequest()
            request.api = api
            request.params['thread_id'] = thread_id
            request.params['message_id'] = msg_id

            delete_message(site, request)
            transaction.commit()

            try:
                raw_msg, msg = self.mbt.get_message(site, from_, 'inbox', thread_id, msg_id)
            except NoSuchThreadException:
                pass
            else:
                raise Exception('Expected a NoSuchThreadException here')

    def test_mark_message_read(self):

        api = uuid.uuid4().hex

        with Replacer() as r:
            r.replace('opencore.views.mbox.authenticated_userid', _authenticated_user_id)

            site, from_, _, msg, thread_id, msg_id, _, _, _, _ = get_data()
            to = find_profiles(site)['admin']
            self.mbt.send_message(site, from_, to, msg, should_commit=True)

            request = DummyRequest()
            request.api = api
            request.params['thread_id'] = thread_id
            request.params['message_id'] = msg_id

            mark_message_read(site, request)
            transaction.commit()

            raw_msg, msg = self.mbt.get_message(site, from_, 'inbox', thread_id, msg_id)
            self.assertEquals(raw_msg.flags, ['READ'])

    def test_get_unread(self):

        api = uuid.uuid4().hex
        user_name = 'admin'

        with Replacer() as r:
            r.replace('opencore.views.mbox.authenticated_userid', _authenticated_user_id)

            site, from_, _, msg, thread_id, msg_id, _, _, _, _ = get_data()
            to = find_profiles(site)[user_name]

            self.mbt.send_message(site, from_, to, msg, should_commit=True)

            request = DummyRequest()
            request.api = api
            request.params['thread_id'] = thread_id
            request.params['message_id'] = msg_id

            mark_message_read(site, request)
            transaction.commit()

            self.mbt.send_message(site, from_, to, msg, should_commit=True)
            transaction.commit()

            unread = self.mbt.get_unread(site, user_name)
            self.assertTrue(unread >= 0)

    def test_format_date(self):
        orig = '2011-05-31 13:59:50'
        expected = '31 May at 13:59'

        site, from_, _, msg, thread_id, msg_id, _, _, _, _ = get_data()

        given = _format_date(site, orig)
        self.assertEquals(expected, given)
Beispiel #7
0
 def send(self, mfrom, profile, msg):
     root = find_site(profile)
     mbt = MailboxTool()
     mbt.send_message(root, mfrom, profile, msg)
Beispiel #8
0
def show_mbox_thread(context, request):
    user = authenticated_userid(request)

    thread_id = request.params.get('thread_id', '')
    mbox_type = _get_mbox_type(request)

    mbt = MailboxTool()
    queues = []
    if mbt.has_queue(context, user, 'inbox', thread_id):
        inbox_q, _, _ = mbt.get_queue_data(context, user, 'inbox', thread_id)
        queues.append(inbox_q)
    if mbt.has_queue(context, user, 'sent', thread_id):
        sent_q, _, _ = mbt.get_queue_data(context, user, 'sent', thread_id)
        queues.append(sent_q)
    unread = mbt.get_unread(context, user, 'inbox')

    messages = []

    return_data = {}

    for q in queues:
        for msg_no in q._messages:
            msg_dict = {}
            raw_msg = q._messages[msg_no]
            raw_msg.flags.append(STATUS_READ)
            message = raw_msg.get()
            from_ = message['From']
            from_profile = request.api.find_profile(from_)

            msg_dict['queue_id'] = q.id
            msg_dict['message_id'] = raw_msg.message_id
            msg_dict['raw_date'] = message['Date']
            msg_dict['date'] = _format_date(context, message['Date'])
            msg_dict['subject'] = message['Subject']
            msg_dict['flags'] = raw_msg.flags

            msg_dict['from'] = from_
            if 'reply_recipients' not in return_data:
                return_data['reply_recipients'] = message['X-people-list'].split(",")
            msg_dict['from_photo'] = _user_photo_url(request, message['From'])
            msg_dict['from_firstname'] = from_profile.firstname
            msg_dict['from_lastname'] = from_profile.lastname
            msg_dict['from_country'] = from_profile.country
            msg_dict['from_organization'] = from_profile.organization
            msg_dict['payload'] = message.get_payload().decode('utf-8')

            to_data = []
            for name in sorted(_to_from_to_header(message)):
                to_datum = {}
                to_profile = request.api.find_profile(name)

                to_datum['name'] = name
                to_datum['firstname'] = to_profile.firstname
                to_datum['lastname'] = to_profile.lastname
                to_datum['photo_url'] = _user_photo_url(request, name)
                to_datum['country'] = to_profile.country
                to_data.append(to_datum)

            msg_dict['to_data'] = to_data

            messages.append(msg_dict)

    return_data['reply_recipients'].remove(user)

    messages.sort(key=itemgetter('raw_date'))

    return_data['profile'] = _get_profile_details(context, request, user)
    return_data['messages'] = messages
    return_data['api'] = request.api
    return_data['mbox_type'] = mbox_type
    return_data['unread'] = unread

    return return_data
Beispiel #9
0
def show_mbox(context, request):
    user = authenticated_userid(request)

    page = request.params.get('page', 1)
    mbox_type = _get_mbox_type(request)

    if not page:
        page = 1

    try:
        page = int(page)
    except ValueError:
        page = 1

    if page < 1:
        page = 1

    mbt = MailboxTool()
    mbox_queues = mbt.get_queues(context, user, mbox_type)
    alternate_mbox_type = 'sent' if mbox_type == 'inbox' else 'inbox'
    unread = mbt.get_unread(context, user, 'inbox')

    pagination = Pagination(page, PER_PAGE, len(mbox_queues))

    # We always count lists from 0, unlike what people do.
    actual_page = page - 1

    # First page ..
    if actual_page == 0:
        start_idx = 0
        end_idx = PER_PAGE

    # .. last page ..
    if not pagination.has_next:
        start_idx = actual_page * PER_PAGE
        end_idx = pagination.total_count

    # .. anything in between
    else:
        start_idx = actual_page * PER_PAGE
        end_idx = (actual_page + 1) * PER_PAGE

    queues = []
    for mbox_q in mbox_queues[start_idx:end_idx]:
        queue = {}
        queue['id'] = mbox_q.id
        queue['name'] = mbox_q.name
        messages = list(mbox_q)
        if mbt.has_queue(context, user, alternate_mbox_type, queue['id']):
            alternate_queue, _, _ = mbt.get_queue_data(context, user,
                    alternate_mbox_type, queue['id'])
            messages += list(alternate_queue)

        sender_names = get_sender_names(request, user, messages)

        queue['total_messages'] = len(messages)
        queue['thread_from'] = ', '.join(sender_names)
        last_message = messages[queue['total_messages'] - 1]
        queue['thread_last_date'] = _format_date(context, last_message['Date'])
        queue['unread'] = mbox_q.get_unread()


        queues.append(queue)

    return_data = {}
    return_data['profile'] = _get_profile_details(context, request, user)
    return_data['queues'] = queues
    return_data['api'] = request.api
    return_data['mbox_type'] = mbox_type
    return_data['unread'] = unread
    return_data['page'] = page

    return return_data
Beispiel #10
0
                        + urlencode({'thread_id': thread_id})
                        + '#last-message')
                return HTTPFound(location=location)
            except Exception, e:
                error_msg = "Couldnt't add a new message, e=[%s]" % traceback.format_exc(e)
                log.error(error_msg)
                return_data['error_msg'] = error_msg
                transaction.abort()
                success = False
            else:
                transaction.commit()
                success = True

            return_data['success'] = success

    mbt = MailboxTool()
    return_data['unread'] = mbt.get_unread(context, user, 'inbox')

    return return_data



def delete_message(context, request):

    user = authenticated_userid(request)

    success = False
    error_msg = ''

    thread_id = request.POST.get('thread_id', '')
    message_id = request.POST.get('message_id', '')
Beispiel #11
0
 def setUp(self):
     self.mbt = MailboxTool()
     self.log = LogCapture()
Beispiel #12
0
class TestMailbox(unittest.TestCase):

    def setUp(self):
        self.mbt = MailboxTool()
        self.log = LogCapture()

    def zztest_send_get_message(self):
        site, from_, to, msg, thread_id, msg_id, _, subject, payload, now = get_data()
        self.mbt.send_message(site, from_, to, msg)

        raw_msg, msg = self.mbt.get_message(site, from_, 'sent', thread_id, msg_id)

        self.assertEquals(raw_msg.message_id, msg_id)
        self.assertEquals(raw_msg.flags, [])

        self.assertEquals(msg['Message-Id'], msg_id)
        self.assertEquals(msg['Subject'], subject)
        self.assertEquals(msg['From'], from_)
        self.assertEquals(msg['To'], ', '.join(to))
        self.assertEquals(msg['Date'],  now)
        self.assertEquals(msg['X-oc-thread-id'], thread_id)
        
        transaction.commit()

    def zztest_delete_message(self):
        site, from_, to, msg, thread_id, msg_id, _, subject, payload, now = get_data()
        self.mbt.send_message(site, from_, to, msg)
        self.mbt.delete_message(site, from_, 'sent', thread_id, msg_id)

        try:
            self.mbt.get_message(site, from_, 'sent', thread_id, msg_id)
        except NoSuchThreadException:
            pass
        else:
            raise
        
        transaction.commit()

    def zztest_set_message_flags(self):
        site, from_, to, msg, thread_id, msg_id, flags, subject, payload, now = get_data()
        self.mbt.send_message(site, from_, to, msg)
        self.mbt.set_message_flags(site, from_, 'sent', thread_id, msg_id, flags)

        raw_msg, msg = self.mbt.get_message(site, from_, 'sent', thread_id, msg_id)
        self.assertEquals(raw_msg.flags, flags)

        raw_msg, msg = self.mbt.get_message(site, from_, 'sent', thread_id, msg_id)
        
        transaction.commit()

    def zztest_get_queues(self):
        site, from_, to, msg, thread_id, msg_id, _, subject, payload, now = get_data()
        self.mbt.send_message(site, from_, to, msg)
        queues = self.mbt.get_queues(site, from_, 'sent')

        for queue in queues:
            self.assertTrue(isinstance(queue, Queue))
            
        transaction.commit()