create_group.py 8.78 KB
Newer Older
1
#!/usr/bin/env python3
2
3
4
5
6
7
import argparse
import re
import yaml
import logging
import logging.handlers

8
from .core import arg_prompt
9
10
11
12
13
14
15
16
17
from subprocess import check_output as cmd
from subprocess import CalledProcessError


class DiscussionGroup:

    def __init__(self, args, config):
        self.__dict__.update(args)
        self.config = config
Rob Carleski's avatar
Rob Carleski committed
18
        self.logger = logging.getLogger(__name__)
19
20

        # Create a sane email address automatically if one isn't specified.
Rob Carleski's avatar
Rob Carleski committed
21
        if not self.email:
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
            self.email = '{}@{}'.format(
                self.name.replace(' ', ''),
                self.config['discussions']['domain']
            )
        elif '@' not in self.email:
            self.email += '@{}'.format(self.config['discussions']['domain'])
        self.email = re.sub(r"[\s'\"]", '', self.email.strip())

    def create_group(self):
        # Create Group
        try:
            cmd([
                self.config['discussions']['gam_command'],
                'create',
                'group',
                self.email,
Rob Carleski's avatar
Rob Carleski committed
38
                'name',
39
                self.name,
Rob Carleski's avatar
Rob Carleski committed
40
                'description',
41
42
                self.description,
                'allow_external_members',
43
                'true',
44
45
            ])
        except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
46
            self.logger.error(e.output, extra={'entity': self.email})
Rob Carleski's avatar
Rob Carleski committed
47
            exit(2)
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

    def add_group_owners(self):
        if hasattr(self, 'owners'):
            for owner in self.owners:
                try:
                    cmd([
                        self.config['discussions']['gam_command'],
                        'update',
                        'group',
                        self.email,
                        'add',
                        'owner',
                        'user',
                        owner
                    ])
                except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
64
                    self.logger.error(
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
                        e.output,
                        extra={'entity': self.email}
                    )
                    continue
        elif hasattr(self, 'owners_file'):
            try:
                cmd([
                    self.config['discussions']['gam_command'],
                    'update',
                    'group',
                    self.email,
                    'add',
                    'owner',
                    'file',
                    self.owners_file
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
82
                self.logger.error(
83
84
85
86
                    e.output,
                    extra={'entity': self.email}
                )
        else:
Rob Carleski's avatar
Rob Carleski committed
87
            self.logger.error(
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
                'No owners assigned to group',
                extra={'entity': self.email}
            )

    def add_group_members(self):
        if hasattr(self, 'members'):
            for member in self.members:
                try:
                    cmd([
                        self.config['discussions']['gam_command'],
                        'update',
                        'group',
                        self.email,
                        'add',
                        'member',
                        'user',
                        member
                    ])
                except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
107
                    self.logger.warning(
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
                        e.output,
                        extra={'entity': self.email}
                    )
                    continue
        elif hasattr(self, 'members_file'):
            try:
                cmd([
                    self.config['discussions']['gam_command'],
                    'update',
                    'group',
                    self.email,
                    'add',
                    'member',
                    'file',
                    self.members_file
                ])
            except CalledProcessError as e:
Rob Carleski's avatar
Rob Carleski committed
125
                self.logger.warning(
126
127
128
129
                    e.output,
                    extra={'entity': self.email}
                )
            except IOError as e:
Rob Carleski's avatar
Rob Carleski committed
130
                self.logger.error(
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
                    e,
                    extra={'entity': self.email}
                )

    def print_canned_text(self):
        print('================================================')
        print('''
Hello!

The new discussion group you requested with the name '{}' has been created
and is ready for use. The email address for this discussion group is '{}'.
Information on managing this group and its members can be found at the
following url:

http://documentation.its.umich.edu/node/578

If you have additional questions or concerns about using this group, please
contact 4HELP at 734.764.4357 or 4HELP@umich.edu.
'''.format(self.name, self.email.lower()))


def main():

    helptext = '''examples:
    discussions-create-group -n collabchat -o jpage@umich.edu bdenver@gmail.com
    discussions-create-group --name collabchat --owners_file /tmp/owners.txt
    '''

    parser = argparse.ArgumentParser(
        description='Creates a new Google discussions group.',
        epilog=helptext,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        '--name',
        '-n',
        help='The name to use for the discussion group.',
    )
    parser.add_argument(
        '--email',
        '-e',
        help='The email address to use for the discussion group.',
    )
174
    owners = parser.add_mutually_exclusive_group()
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
    owners.add_argument(
        '--owners',
        '-o',
        help='The full email address(es) of group owners.',
        nargs='+'
    )
    owners.add_argument(
        '--owners_file',
        '-O',
        help='The location of a file containing a list of group owners.'
    )
    members = parser.add_mutually_exclusive_group()
    members.add_argument(
        '--members',
        '-m',
        help='The full email address(es) of group members.',
        nargs='+',
        default=[]
    )
    members.add_argument(
        '--members_file',
        '-M',
        help='The location of a file containing a list of group members.'
    )
    parser.add_argument(
        '--description',
        '-d',
        help='A description of the group.',
        default=''
    )
    parser.add_argument(
        '--config',
        '-c',
        help='The CAK config file to use.',
        default='/etc/collab-admin-kit.yml'
    )
    args = parser.parse_args()

213
214
215
216
217
218
219
220
221
222
    # Argument prompt fallback
    if not args.name:
        args.name = arg_prompt(
            'Group display name'
        )
        args.email = arg_prompt(
            '(optional) Local part to be used for the group email address',
            default=''
        )
        args.owners = arg_prompt(
Rob Carleski's avatar
Rob Carleski committed
223
            '(option 1) Full email addresses of owners, separated by commas',
224
            default=''
Rob Carleski's avatar
Rob Carleski committed
225
226
227
228
229
230
        ).split(',')
        print(args.owners)
        if not args.owners[0]:
            args.owners_file = arg_prompt(
                '(option 2) Full file path to a list of owners'
            )
231
        args.members = arg_prompt(
Rob Carleski's avatar
Rob Carleski committed
232
            '(option 1) Full email addresses of members, separated by commas',
233
            default=''
Rob Carleski's avatar
Rob Carleski committed
234
235
236
237
238
        ).split(',')
        if not args.members[0]:
            args.members_file = arg_prompt(
                '(option 2) The full file path to a list of members'
            )
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
        args.description = arg_prompt(
            '(optional) Description to assign to the group',
            default=''
        )

    # Argument sanity check
    _required = [
        'name',
        ('owners', 'owners_file'),
        ('members', 'members_file')
    ]
    for r in _required:
        try:
            if isinstance(r, str):
                assert getattr(args, r)
            if isinstance(r, tuple):
                assert getattr(args, r[0]) or getattr(args, r[1])
        except AssertionError:
            print('Missing required argument {}'.format(r))

259
260
261
262
263
    # Open the CAK Config
    with open(args.config) as stream:
        config = yaml.load(stream, Loader=yaml.BaseLoader)

    # Get the root logger and set the debug level
Rob Carleski's avatar
Rob Carleski committed
264
    logger = logging.getLogger(__name__)
265
266
267
268
269
270
271
272
273
274
275
276
277
    logger.setLevel(logging.DEBUG)

    # Create a syslog handler, set format, and associate.
    sh = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=config['general']['log_facility']
    )
    formatter = logging.Formatter(config['general']['log_format'])
    sh.setFormatter(formatter)
    logger.addHandler(sh)

    # Create a console handler, set format, and associate.
    ch = logging.StreamHandler()
278
279
280
281
    formatter = logging.Formatter(
        config['general']['console_format'],
        config['general']['date_format']
    )
282
283
284
    ch.setFormatter(formatter)
    logger.addHandler(ch)

285
    group = DiscussionGroup(vars(args), config)
286
287
288
289
290
291
292
293
    group.create_group()
    group.add_group_owners()
    group.add_group_members()
    group.print_canned_text()


if __name__ == '__main__':
    main()