aboutsummaryrefslogtreecommitdiffstats
path: root/bin/list_members
blob: cb574081715857c50edc8d2115ea1686db4bb57d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#! @PYTHON@
#
# Copyright (C) 1998-2003 by the Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

"""List all the members of a mailing list.

Usage: %(PROGRAM)s [options] listname

Where:

    --output file
    -o file
        Write output to specified file instead of standard out.

    --regular / -r
        Print just the regular (non-digest) members.

    --digest[=kind] / -d [kind]
        Print just the digest members.  Optional argument can be "mime" or
        "plain" which prints just the digest members receiving that kind of
        digest.

    --nomail[=why] / -n [why]
        Print the members that have delivery disabled.  Optional argument can
        be "byadmin", "byuser", "bybounce", or "unknown" which prints just the
        users who have delivery disabled for that reason.  It can also be
        "enabled" which prints just those member for whom delivery is
        enabled.

    --fullnames / -f
        Include the full names in the output.

    --preserve / -p
        Output member addresses case preserved the way they were added to the
        list.  Otherwise, addresses are printed in all lowercase.

    --invalid / -i
        Print only the addresses in the membership list that are invalid.
        Ignores -r, -d, -n.

    --unicode / -u
        Print addresses which are stored as Unicode objects instead of normal
        string objects.  Ignores -r, -d, -n.

    --help
    -h
        Print this help message and exit.

    listname is the name of the mailing list to use.

Note that if neither -r or -d is supplied, both regular members are printed
first, followed by digest members, but no indication is given as to address
status.
"""

import sys
from types import UnicodeType

import paths
from Mailman import mm_cfg
from Mailman import Utils
from Mailman import MailList
from Mailman import Errors
from Mailman import MemberAdaptor
from Mailman.i18n import _

from email.Utils import formataddr

PROGRAM = sys.argv[0]
ENC = sys.getdefaultencoding()
COMMASPACE = ', '

try:
    True, False
except NameError:
    True = 1
    False = 0


WHYCHOICES = {'enabled' : MemberAdaptor.ENABLED,
              'unknown' : MemberAdaptor.UNKNOWN,
              'byuser'  : MemberAdaptor.BYUSER,
              'byadmin' : MemberAdaptor.BYADMIN,
              'bybounce': MemberAdaptor.BYBOUNCE,
              }


def usage(code, msg=''):
    if code:
        fd = sys.stderr
    else:
        fd = sys.stdout
    print >> fd, _(__doc__)
    if msg:
        print >> fd, msg
    sys.exit(code)



def safe(s):
    if not s:
        return ''
    if isinstance(s, UnicodeType):
        return s.encode(ENC, 'replace')
    return unicode(s, ENC, 'replace').encode(ENC, 'replace')


def isinvalid(addr):
    try:
        Utils.ValidateEmail(addr)
        return False
    except Errors.EmailAddressError:
        return True

def isunicode(addr):
    return isinstance(addr, UnicodeType)



def whymatches(mlist, addr, why):
    # Return true if the `why' matches the reason the address is enabled, or
    # in the case of why is None, that they are disabled for any reason
    # (i.e. not enabled).
    status = mlist.getDeliveryStatus(addr)
    if why is None:
        return status <> MemberAdaptor.ENABLED
    return status == WHYCHOICES[why]



def main():
    # Because of the optional arguments, we can't use getopt. :(
    outfile = None
    regular = None
    digest = None
    preserve = None
    nomail = None
    why = None
    kind = None
    fullnames = False
    invalidonly = False
    unicodeonly = False

    # Throw away the first (program) argument
    args = sys.argv[1:]
    if not args:
        usage(0)

    while True:
        try:
            opt = args.pop(0)
        except IndexError:
            usage(1)
        if opt in ('-h', '--help'):
            usage(0)
        elif opt in ('-f', '--fullnames'):
            fullnames = True
        elif opt in ('-p', '--preserve'):
            preserve = True
        elif opt in ('-r', '--regular'):
            regular = True
        elif opt in ('-o', '--output'):
            try:
                outfile = args.pop(0)
            except IndexError:
                usage(1)
        elif opt == '-n':
            nomail = True
            if args and args[0] in WHYCHOICES.keys():
                why = args.pop(0)
        elif opt.startswith('--nomail'):
            nomail = True
            i = opt.find('=')
            if i >= 0:
                why = opt[i+1:]
                if why not in WHYCHOICES.keys():
                    usage(1, _('Bad --nomail option: %(why)s'))
        elif opt == '-d':
            digest = True
            if args and args[0] in ('mime', 'plain'):
                kind = args.pop(0)
        elif opt.startswith('--digest'):
            digest = True
            i = opt.find('=')
            if i >= 0:
                kind = opt[i+1:]
                if kind not in ('mime', 'plain'):
                    usage(1, _('Bad --digest option: %(kind)s'))
        elif opt in ('-i', '--invalid'):
            invalidonly = True
        elif opt in ('-u', '--unicode'):
            unicodeonly = True
        else:
            # No more options left, push the last one back on the list
            args.insert(0, opt)
            break

    if len(args) <> 1:
        usage(1)

    listname = args[0].lower().strip()

    if regular is None and digest is None:
        regular = digest = True

    if outfile:
        try:
            fp = open(outfile, 'w')
        except IOError:
            print >> sys.stderr, _('Could not open file for writing:'), outfile
            sys.exit(1)
    else:
        fp = sys.stdout

    try:
        mlist = MailList.MailList(listname, lock=False)
    except Errors.MMListError, e:
        print >> sys.stderr, _('No such list: %(listname)s')
        sys.exit(1)

    # Get the lowercased member addresses
    rmembers = mlist.getRegularMemberKeys()
    dmembers = mlist.getDigestMemberKeys()

    if preserve:
        # Convert to the case preserved addresses
        rmembers = mlist.getMemberCPAddresses(rmembers)
        dmembers = mlist.getMemberCPAddresses(dmembers)

    if invalidonly or unicodeonly:
        all = rmembers + dmembers
        all.sort()
        for addr in all:
            name = fullnames and mlist.getMemberName(addr) or ''
            showit = False
            if invalidonly and isinvalid(addr):
                showit = True
            if unicodeonly and isunicode(addr):
                showit = True
            if showit:
                print >> fp, formataddr((safe(name), addr))
        return
    if regular:
        rmembers.sort()
        for addr in rmembers:
            name = fullnames and mlist.getMemberName(addr) or ''
            # Filter out nomails
            if nomail and not whymatches(mlist, addr, why):
                continue
            print >> fp, formataddr((safe(name), addr))
    if digest:
        dmembers.sort()
        for addr in dmembers:
            name = fullnames and mlist.getMemberName(addr) or ''
            # Filter out nomails
            if nomail and not whymatches(mlist, addr, why):
                continue
            # Filter out digest kinds
            if mlist.getMemberOption(addr, mm_cfg.DisableMime):
                # They're getting plain text digests
                if kind == 'mime':
                    continue
            else:
                # They're getting MIME digests
                if kind == 'plain':
                    continue
            print >> fp, formataddr((safe(name), addr))



if __name__ == '__main__':
    main()