def test_post_to_private_list_accepted_members(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=True, postperm="MEMBERS")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=True)
     PermissionCache(self.env, 'sparrowj',
                     mailinglist.resource).assert_permission('MAILINGLIST_POST')
 def test_adding_lists(self):
     for i in range(0,10):
         mailinglist = Mailinglist(self.env,
                                   emailaddress="list%s" % i, name="Sample List", private=True,
                                   postperm="OPEN")
         mailinglist.insert()
         assert mailinglist.addr()
         assert mailinglist.addr(bounce=True)            
 def test_read_private_list_denied(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=True, postperm="RESTRICTED")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=False)        
     mailinglist.subscribe(user="******", poster=True)
     PermissionCache(self.env, 'randomuser',
                     mailinglist.resource).assert_permission('MAILINGLIST_VIEW')
 def test_post_to_private_list_accepted_restricted(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=True, postperm="RESTRICTED")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=False)        
     mailinglist.subscribe(user="******", poster=True)
     PermissionCache(self.env, 'sparrowj',
                     mailinglist.resource).assert_permission('MAILINGLIST_POST')
 def test_post_to_private_list_denied_restricted_nonmember(self):
     """Non-posting member of this list."""        
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=True, postperm="RESTRICTED")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=False)
     PermissionCache(self.env, 'smithj',
                     mailinglist.resource).assert_permission('MAILINGLIST_POST')
 def test_load_list(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="list", name="Sample List", private=True,
                               postperm="OPEN")
     assert mailinglist.id is None
     mailinglist.insert()
     assert mailinglist.id is not None
     found = Mailinglist(self.env, mailinglist.id)
     assert found.id is mailinglist.id
 def test_post_to_private_list_accepted_members_group(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=True, postperm="MEMBERS")
     mailinglist.insert()
     PermissionSystem(self.env).grant_permission('sparrowj', 'group1')
     PermissionSystem(self.env).grant_permission('smithj', 'group1')        
     mailinglist.subscribe(group="group1", poster=True)
     PermissionCache(self.env, 'sparrowj',
                     mailinglist.resource).assert_permission('MAILINGLIST_POST')
 def test_read_nonprivate_list_accepted(self):
     PermissionSystem(self.env).grant_permission('members', 'MAILINGLIST_VIEW')
     PermissionSystem(self.env).grant_permission('randomuser', 'members')
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=False, postperm="RESTRICTED")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=False)        
     mailinglist.subscribe(user="******", poster=True)
     PermissionCache(self.env, 'randomuser',
                     mailinglist.resource).assert_permission('MAILINGLIST_VIEW')
 def test_read_nonprivate_list_denied(self):
     # not a private list, but in general the user isn't allowed to
     # view mailing lists (e.g., not a member of this project at all.)
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=False, postperm="RESTRICTED")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=False)        
     mailinglist.subscribe(user="******", poster=True)
     PermissionCache(self.env, 'randomuser',
                     mailinglist.resource).assert_permission('MAILINGLIST_VIEW')
 def test_removing_lists(self):
     l = []
     for i in range(0,10):
         mailinglist = Mailinglist(self.env,
                                   emailaddress="list%s" % i, name="Sample List", private=True,
                                   postperm="OPEN")
         mailinglist.insert()
         l.append(mailinglist.id)
         
     for i in l:
         Mailinglist(self.env, i).delete()
    def test_subscribers(self):
        mailinglist = Mailinglist(self.env,
                                  emailaddress="LIST1", private=True, postperm="MEMBERS")
        mailinglist.insert()
        PermissionSystem(self.env).grant_permission('sparrowj', 'group1')
        PermissionSystem(self.env).grant_permission('smithj', 'group1')
        PermissionSystem(self.env).grant_permission('pipern', 'group2')
        mailinglist.subscribe(group="group1", poster=True)
        mailinglist.subscribe(group="group2", poster=True)
        mailinglist.unsubscribe(user="******")

        assert mailinglist.subscribers()["smithj"]['decline'] == True
        assert "sparrowj" in mailinglist.subscribers()
        assert "pipern" in mailinglist.subscribers()

        mailinglist.unsubscribe(group="group1")
        assert "sparrowj" not in mailinglist.subscribers()        
    def import_mailinglist(self, template_path):
        """Creates project mailing lists from mailinglist.xml template file."""

        path = os.path.join(template_path, 'mailinglist.xml')
        try:
            tree = ET.ElementTree(file=path)
            for ml in tree.getroot():
                mailinglist = Mailinglist(self.env, emailaddress=ml.attrib['email'],
                                               name=ml.attrib['name'],
                                               description=ml.text,
                                               private=ml.attrib['private'],
                                               postperm=ml.attrib['postperm'],
                                               replyto=ml.attrib['replyto'])
                mailinglist.insert()
        except IOError as exception:
            if exception.errno == errno.ENOENT:
                self.log.info("Path to mailinglist.xml at %s does not exist. "
                              "Unable to import mailing lists from template.", path)
 def test_update_private(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="list", name="Sample List", private=True,
                               postperm="OPEN")
     assert mailinglist.private == True
     newid = mailinglist.insert()
     mailinglist.private = False
     mailinglist.save_changes()
     assert Mailinglist(self.env, newid).private is False
 def test_add_message_with_attachment(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", name="Sample List 1", private=True,
                               postperm="OPEN")
     mailinglist.insert()
     
     mailinglist.insert_raw_email(raw_message_with_attachment % dict(sender="Jack Sparrow",
                                                                     email="*****@*****.**",
                                                                     list="list1",
                                                                     domain="example.com",
                                                                     subject="Boats",
                                                                     asctime=time.asctime(),
                                                                     id="asdfasdf",
                                                                     body="Need images of boats."))
     
     message = mailinglist.conversations().next().messages().next()
     attachment_path = Attachment.select(self.env, message.resource.realm, message.resource.id).next().path
     assert os.path.exists(attachment_path)        
     message.delete()
     assert not os.path.exists(attachment_path)
    def test_add_messages(self):
        mailinglist = Mailinglist(self.env,
                                  emailaddress="LIST1", name="Sample List 1", private=True,
                                  postperm="OPEN")
        mailinglist.insert()
        mailinglist = Mailinglist(self.env,
                                  emailaddress="list2", name="Sample List 2", private=True,
                                  postperm="OPEN")
        mailinglist.insert()

        for rawmsg in rawmsgs:
            for listname in ("list1", "list2"):
                bytes = rawmsg % dict(sender="Jack Sparrow",
                                      email="*****@*****.**",
                                      list=listname,
                                      domain="example.com",
                                      subject="Boats",
                                      asctime=time.asctime(),
                                      id="asdfasdf",
                                      body="Need boats.")

                mailinglist = Mailinglist.select_by_address(self.env,
                                                            "*****@*****.**" % listname)
                message = mailinglist.insert_raw_email(bytes)
                
        assert len(list(Mailinglist.select(self.env))) == 2
        
        for mailinglist in Mailinglist.select(self.env):
            for conversation in mailinglist.conversations():
                assert conversation.get_first() is not None
                for message in conversation.messages():
                    assert message
                    #for attachment in Attachment.select(self.env, 'mailinglistmessage', message.id):
                    #    assert attachment

            mailinglist.delete()
            
        assert len(list(Mailinglist.select(self.env))) == 0
    def import_project(self, sourcepath, destinationpath, name=None, **kwargs):

        if name is None:
            raise KeyError("This importer requires a Trac project to already exist. Use --name to specify its dir name.")
        
        env_path = os.path.join(destinationpath, name)
        mailinglist_name = os.path.basename(sourcepath.rstrip("/"))
        env = open_environment(env_path)

        #mailinglist = Mailinglist.select_by_address(env, mailinglist_name, localpart=True)
        #mailinglist.delete()

        try:
            mailinglist = Mailinglist.select_by_address(env, mailinglist_name, localpart=True)
        except ResourceNotFound:
            mailinglist = Mailinglist(env, emailaddress=mailinglist_name, name="Imported list",
                                      private=True, postperm="MEMBERS", replyto="LIST")
            mailinglist.insert()

        mbox = mailbox.Maildir(sourcepath)

        for mail in mbox:
            mail.fp.seek(0)
            mailinglist.insert_raw_email(mail.fp.read())
 def read_file(self, mbox_file, metadata=None):
     mailinglist_name = os.path.basename(mbox_file).rstrip('mbox.gz')
     if not metadata:
         metadata = dict(emailaddress=mailinglist_name,
                         name='%s (Imported)' % mailinglist_name,
                         private=True,
                         postperm='MEMBERS',
                         replyto='LIST',
                         date=datetime.utcnow(),
                         individuals=[],
                         groups=[],
                         declines=[])
     individuals = metadata.pop('individuals')
     groups = metadata.pop('groups')
     declines = metadata.pop('declines')
     try:
         mailinglist = Mailinglist.select_by_address(self.env, mailinglist_name, localpart=True)
     except ResourceNotFound:
         mailinglist = Mailinglist(self.env, **metadata)
         try:
             mailinglist.insert()
         except Exception, e:
             self.log.exception(metadata)
             raise
    def render_admin_panel(self, req, cat, page, mailinglist_emailpart):
        req.perm.require('MAILINGLIST_ADMIN')

        if mailinglist_emailpart:
            mailinglist = Mailinglist.select_by_address(self.env,
                                                        mailinglist_emailpart,
                                                        localpart=True)
            if req.method == 'POST':
                if req.args.get('save'):
                    mailinglist.name = req.args.get('name')
                    mailinglist.private = req.args.get('private') == 'PRIVATE'
                    mailinglist.postperm = req.args.get('postperm')
                    mailinglist.replyto = req.args.get('replyto')
                    mailinglist.description = req.args.get('description')
                    if 'TRAC_ADMIN' in req.perm:
                        mailinglist.emailaddress = req.args.get('emailaddress')
                    mailinglist.save_changes()
                    add_notice(req, _('Your changes have been saved.'))
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('cancel'):
                    req.redirect(req.href.admin(cat, page))
                elif req.args.get('subscribeuser'):
                    @self.env.with_transaction()
                    def do_subscribe(db):
                        mailinglist = Mailinglist.select_by_address(self.env, mailinglist_emailpart,
                                                                    localpart=True, db=db)
                        mailinglist.subscribe(user=req.args['username'], db=db)
                    add_notice(req, _('The user %s has been subscribed.') % req.args['username'])
                    
                    req.redirect(req.href.admin(cat, page, mailinglist_emailpart))
                elif req.args.get('removeusers'):
                    sel = req.args.get('sel')
                    if not sel:
                        raise TracError(_('No users selected'))
                    if not isinstance(sel, list):
                        sel = [sel]
                    @self.env.with_transaction()
                    def do_remove(db):
                        mailinglist = Mailinglist.select_by_address(self.env, mailinglist_emailpart,
                                                                    localpart=True, db=db)
                        for username in sel:
                            mailinglist.unsubscribe(user=username, db=db)
                    add_notice(req, _('The selected users have been unsubscribed.'))
                    
                    req.redirect(req.href.admin(cat, page, mailinglist_emailpart))
                elif req.args.get('subscribegroup'):
                    @self.env.with_transaction()
                    def do_subscribe(db):
                        mailinglist = Mailinglist.select_by_address(self.env, mailinglist_emailpart,
                                                                    localpart=True, db=db)
                        mailinglist.subscribe(group=req.args['groupname'], db=db)
                    add_notice(req, _('The group %s has been subscribed.') % req.args['groupname'])
                    
                    req.redirect(req.href.admin(cat, page, mailinglist_emailpart))                    
                elif req.args.get('removegroups'):
                    sel = req.args.get('sel')
                    if not sel:
                        raise TracError(_('No groups selected'))
                    if not isinstance(sel, list):
                        sel = [sel]
                    @self.env.with_transaction()
                    def do_remove(db):
                        mailinglist = Mailinglist.select_by_address(self.env, mailinglist_emailpart,
                                                                    localpart=True, db=db)
                        for username in sel:
                            mailinglist.unsubscribe(group=username, db=db)
                    add_notice(req, _('The selected groups have been unsubscribed.'))
                    
                    req.redirect(req.href.admin(cat, page, mailinglist_emailpart))
                elif req.args.get('updatepostergroups') or req.args.get('updateposterusers'):
                    sel = req.args.get('sel')
                    if not sel:
                        sel = []
                    if not isinstance(sel, list):
                        sel = [sel]
                    @self.env.with_transaction()
                    def do_update(db):
                        mailinglist = Mailinglist.select_by_address(self.env, mailinglist_emailpart,
                                                                    localpart=True, db=db)
                        if req.args.get('updatepostergroups'):
                            current_statuses =  mailinglist.groups()
                        else:
                            current_statuses =  mailinglist.individuals()
                        for subname, poster in current_statuses:
                            if req.args.get('updatepostergroups'):                            
                                updater = partial(mailinglist.update_poster, group=subname)
                            else:
                                updater = partial(mailinglist.update_poster, user=subname)                            
                            if poster and subname not in sel:
                                updater(poster=False)
                            elif not poster and subname in sel:
                                updater(poster=True)
                            
                    add_notice(req, _('Posters have been updated.'))
                    
                    req.redirect(req.href.admin(cat, page, mailinglist_emailpart))
                    

            Chrome(self.env).add_wiki_toolbars(req)

            if self.env.is_component_enabled('simplifiedpermissionsadminplugin.simplifiedpermissions.SimplifiedPermissions'):
                from simplifiedpermissionsadminplugin.simplifiedpermissions import SimplifiedPermissions
                # groups is used for subscription, so it should not have subscribed groups in it
                groups = set(SimplifiedPermissions(self.env).groups) - set([subscribed_group for subscribed_group, group_poster in mailinglist.groups()])
            else:
                groups = None
            
            data = {'view': 'detail',
                    'mailinglist': mailinglist,
                    'groups': groups,
                    'email_domain': MailinglistSystem(self.env).email_domain}
        else:
            if req.method == 'POST':
                if req.args.get('add') and req.args.get('emailaddress'):
                    emailaddress = req.args['emailaddress'].lower()
                    try:
                        mailinglist = Mailinglist.select_by_address(self.env, emailaddress, localpart=True)
                    except ResourceNotFound:
                        mailinglist = Mailinglist(self.env, name=req.args['name'])
                        mailinglist.private = req.args.get('private') == 'PRIVATE'
                        mailinglist.postperm = req.args.get('postperm')
                        mailinglist.replyto = req.args.get('replyto')
                        mailinglist.emailaddress = req.args.get('emailaddress')
                        mailinglist.insert()
                        add_notice(req, _('The mailinglist "%(addr)s" has been '
                                          'added.', addr=mailinglist.addr()))
                        req.redirect(req.href.admin(cat, page))
                    else:
                        raise TracError(_('Mailinglist with email address %(emailaddress)s already exists.',
                                          emailaddress=emailaddress))
                # Remove mailinglists
                elif req.args.get('remove'):
                    req.perm.require('TRAC_ADMIN')
                    sel = req.args.get('sel')
                    if not sel:
                        raise TracError(_('No mailinglist selected'))
                    if not isinstance(sel, list):
                        sel = [sel]
                    @self.env.with_transaction()
                    def do_remove(db):
                        for email in sel:
                            mailinglist = Mailinglist.select_by_address(self.env, email,
                                                                        localpart=True, db=db)
                            mailinglist.delete(db=db)
                    add_notice(req, _('The selected mailinglists have been '
                                      'removed.'))
                    req.redirect(req.href.admin(cat, page))
                    
                    
            mailinglists = Mailinglist.select(self.env)
            
            data = {'view': 'list',
                    'mailinglists': mailinglists,
                    'email_domain': MailinglistSystem(self.env).email_domain}                    
            
        return ('mailinglist_admin.html', data)
 def test_add_list_member(self):
     mailinglist = Mailinglist(self.env,
                               emailaddress="LIST1", private=True, postperm="MEMBERS")
     mailinglist.insert()
     mailinglist.subscribe(user="******", poster=True)
     assert "sparrowj" in mailinglist.subscribers()