1#!/usr/bin/env python3
2
3"""Helper tool for accessing the EMAIL_RECEIVERS and EMAIL_SUBSCRIPTIONS tables
4controlling how and when users are sent email notifications."""
5
6from chart.common.args import ArgumentParser
7from chart.common.prettyprint import Table
8from chart.web.user import User
9
10
11def show_user(user):
12 """Dump info about user to terminal."""
13 t = Table()
14 t.append(('Properties', user.properties))
15 t.write()
16
17
18def list_users():
19 """Print table of all users to terminal.
20 """
21
22 t = Table(title='All email receivers',
23 headings=('Id', 'User', 'Name', 'Email'))
24
25 for u in User.all():
26 t.append((u.user_id, u.username, u.complete_name, u.email))
27
28 t.write()
29
30
31def main():
32 """Command line entry point"""
33
34 parser = ArgumentParser(__doc__)
35 parser.add_argument('--id',
36 type=int,
37 help='Specify user id')
38 parser.add_argument('--name',
39 help='Specify user name')
40 parser.add_argument('--list', '-l',
41 action='store_true',
42 help='List all users')
43 args = parser.parse_args()
44 if args.id:
45 u = User.from_db(user_id=args.id)
46 show_user(u)
47 parser.exit()
48
49 if args.name:
50 u = User.from_db(username=args.name)
51 show_user(u)
52 parser.exit()
53
54 if args.list:
55 list_users()
56 parser.exit()
57
58 # else:
59 # db.query('
60
61if __name__ == '__main__':
62 main()
63
64# import sys
65
66# from chart.common.prettyprint import Table
67# from chart.common.args import ArgumentParser
68# from chart.common.log import init_log
69# from chart import db
70# from chart.common.tables import TableInfo
71
72
73# def show_all_recs():
74 # """Display all configured email receivers."""
75
76 # for row in db.query('SELECT id, username, first_name, last_name, email '
77 # 'FROM auth_user '
78 # 'ORDER BY username'):
79 # t.append(row)
80
81 # t.write()
82
83
84# def show_rec(rec):
85 # """Display information about a single email receiver."""
86
87 # address, name = db.query(
88 # 'SELECT address,name FROM email_receivers WHERE id=:rec', rec=rec).fetchone()
89
90 # t = Table(title='Receiver info')
91 # t.append(('Id', ': ' + str(rec)))
92 # t.append(('Name', ': ' + name))
93 # t.append(('Address', ': ' + address))
94 # t.write()
95
96 # print ''
97
98 # t = Table(title='Subscriptions',
99 # headings=('Id', 'Subscription type', 'Name filter', 'SCID filter'))
100 # map(t.append, db.query('SELECT id,subscription_type,name_filter,scid_filter '
101 # 'FROM email_subscriptions WHERE receiver_id=:rec ORDER BY id',
102# rec=rec))
103
104 # t.write()
105
106
107# def show_sub(rec, sub): # (unused argument) pylint: disable=W0613
108# """TBD: display details of a subscription."""
109# pass
110
111
112# def action_show(args):
113 # """Provide the --show option, either giving:
114
115 # * A list of all email receivers
116 # * Details about a single receiver
117 # * Full details about one subscription for a single receiver
118 # """
119
120 # if not args.rec and not args.sub:
121 # show_all_recs()
122
123 # elif args.rec and not args.sub:
124 # show_rec(args.rec)
125
126 # elif args.sub:
127 # show_sub(args.rec, args.sub)
128
129
130# def add_rec(args):
131# """Configure a new receiver."""
132
133# print 'Adding new receiver\n-------------------\n'
134
135# if args.name is None:
136# print 'Enter name'
137# # raw_input instead?
138# args.name = sys.stdin.readline().strip()
139
140# if args.address is None:
141# print 'Enter email address'
142# args.address = sys.stdin.readline().strip()
143
144# if not args.address.endswith('@eumetsat.int'):
145# print 'WARNING: addresses which are not internal EUMETSAT addresses may not be accessible'
146
147# rec_id = db.query_insert_with_return(
148# "INSERT INTO email_receivers (name,address) VALUES (:name, :address) ",
149# 'id',
150# name=args.name,
151# address=args.address)
152# db.commit()
153# print 'Added receiver {id}'.format(id=rec_id)
154
155
156# def add_sub(rec, sub_type, name_filter, scid_filter):
157# """Configure a new subscription."""
158
159# #if rec is None:
160# # print 'Enter receiver ID'
161# # rec = int(sys.stdin.readline().strip())
162# # validate user input here
163
164# if sub_type is None:
165# print 'Enter subscription type'
166# print TableInfo('EMAIL_SUBSCRIPTIONS').fields['SUBSCRIPTION_TYPE'].description
167# sub_type = sys.stdin.readline().strip()
168
169# skip_name_filter = False
170# if sub_type == 'daily-digest':
171# skip_name_filter = True
172
173# if name_filter is not None:
174# skip_name_filter = True
175
176# while not skip_name_filter:
177# print ''
178# if sub_type == 'event-alert':
179# print "Enter name-filter as an Oracle LIKE expression. "\
180# "Use '%' to filter for all names. "\
181# "Type '?' to see a list of event names in the EVENTS table. "\
182# "Type '? <exp>' so test <exp> against the list of current extant events."
183# name_filter = sys.stdin.readline().strip()
184# if name_filter == '?':
185# print '\nAll event names:'
186# for event_classname, in db.query(
187# "SELECT event_class FROM events GROUP BY event_class ORDER BY event_class"):
188# print event_classname
189
190# elif name_filter.startswith('? '):
191# name_filter = name_filter[2:]
192# print "\nEvent names matching '{filter}':".format(filter=name_filter)
193# for event_classname, in db.query("SELECT event_class FROM events "
194# "WHERE event_class LIKE :filter "
195# "GROUP BY event_class ORDER BY event_class",
196# filter=name_filter):
197# print event_classname
198
199# elif len(name_filter) == 0:
200# print 'Name filter cannot be empty for event-alert subscriptions'
201
202# else:
203# skip_name_filter = True
204
205# elif sub_type in ('alg-alert', 'alg-error'):
206# print "Enter name-filter as an Oracle LIKE expression. "\
207# "Use '%' to include all algorithms. Type '?' to see a list of all "\
208# "algorithm names in the ALGORITHMS table. Type '? <exp>' to test <ext> "\
209# "against the list of algorithms currently in use."
210# name_filter = sys.stdin.readline().strip()
211# if name_filter == '?':
212# print '\nAll algorithms:'
213# for alg, in db.query("SELECT algorithm FROM algorithms "
214# "GROUP BY algorithm ORDER BY algorithm"):
215# print alg
216
217# elif name_filter.startswith('? '):
218# name_filter = name_filter[2:]
219# print "\nAlgorithm names matching '{filter}':".format(filter=name_filter)
220# for alg, in db.query("SELECT algorithm FROM algorithms "
221# "WHERE algorithm LIKE :filter "
222# "GROUP BY algorithm ORDER BY algorithm",
223# filter=name_filter):
224# print alg
225
226# elif len(name_filter) == 0:
227# print 'Name filter cannot be empty for alg-alert or alg-error subscriptions'
228
229# else:
230# skip_name_filter = True
231
232# else:
233# print "Enter name-filter as an Oracle LIKE expression. "\
234# "Use '%' to filter for all names"
235# name_filter = sys.stdin.readline().strip()
236# skip_name_filter = True
237
238# if scid_filter is None:
239# if sub_type in ('event-alert', 'alg-alert', 'alg-error'):
240# while scid_filter in (None, ''):
241# print "\nEnter SCID-filter as an Oracle LIKE expression. "\
242# "Use '%' to accept all SCIDs"
243# scid_filter = sys.stdin.readline().strip()
244# if len(scid_filter) == 0:
245# print "\nCannot use empty SCID filter for this subscription type. "\
246# "Try 'SYS' for non-satellite specific subscriptions or '%' for all SCIDs."
247
248# else:
249# print "\nEnter SCID-filter as an Oracle LIKE expression (leave as empty "\
250# "if SCID filter is not appropriate, or type '%' to accept all SCIDs)"
251# scid_filter = sys.stdin.readline().strip()
252
253# sub_id = db.query_insert_with_return(
254# "INSERT INTO email_subscriptions "
255# " (receiver_id, subscription_type, name_filter, scid_filter) "
256# "VALUES"
257# " (:receiver_id, :sub_type, :name_filter, :scid_filter)",
258# 'id',
259# receiver_id=rec,
260# sub_type=sub_type,
261# name_filter=name_filter,
262# scid_filter=scid_filter)
263# db.commit()
264# print '\nAdded subscription {id} for receiver {rec}'.format(id=sub_id, rec=rec)
265
266
267# def action_add(args):
268# """Perform the --add command, adding either a new receiver or
269# adding a subscription to an existing receiver, depending on whether the
270# user passed an '--rec' option.
271# """
272
273# if args.rec is None and args.sub is None:
274# add_rec(args)
275# elif args.rec and args.sub is None:
276# add_sub(args.rec, args.sub_type, args.name_filter, args.scid_filter)
277# else:
278# raise Exception('Omit --rec to add a new receiver, or specify --rec '
279# 'to add a subscription to an existing receiver')
280
281
282# def remove_rec(rec):
283# """Delete a receiver."""
284
285# sql = "DELETE FROM email_subscriptions WHERE receiver_id={rec}".format(rec=rec)
286# print sql
287# db.query(sql)
288# sql = "DELETE FROM email_receivers WHERE id={rec}".format(rec=rec)
289# print sql
290# db.query(sql)
291# db.commit()
292
293
294# def remove_sub(sub):
295# """Delete a subscription from a subscription."""
296
297# if db.query("SELECT count(*) FROM email_subscriptions WHERE id=:sub", sub=sub).\
298# fetchone()[0] == 0:
299# print 'Subscription {sub} not found'.format(sub=sub)
300
301# sub_id, rec_id, sub_type, name_filter, scid_filter = db.query(
302# "SELECT id,receiver_id,subscription_type,name_filter,scid_filter "
303# "FROM email_subscriptions WHERE id=:sub", sub=sub).fetchone()
304
305# name, address = db.query("SELECT name,address FROM email_receivers WHERE id=:rec",
306# rec=rec_id).fetchone()
307
308# print 'Removing subscription {sub} ({sub_type} for {name_filter} on '\
309# '{scid_filter}) from receiver {rec} ({name}, {address})'.format(
310# sub=sub_id, sub_type=sub_type, name_filter=name_filter, scid_filter=scid_filter,
311# rec=rec_id, name=name, address=address)
312
313# sql = 'DELETE FROM email_subscriptions WHERE id={sub}'.format(sub=sub)
314# print sql
315# db.query(sql)
316# db.commit()
317
318
319# def action_remove(args):
320# """Perform the --remove option, removing either a subscription
321# or receiver depending on whether just --rec or --rec and --sub
322# were specified."""
323
324# if args.rec is not None and args.sub is None:
325# remove_rec(args.rec)
326# elif args.sub is not None:
327# remove_sub(args.sub)
328# else:
329# raise Exception('Specify either --rec to remove a receiver or '
330# '--sub to remove a subscription')
331
332# if __name__ == '__main__':
333 # init_log()
334
335 # actions = {'show': action_show,
336 # 'remove': action_remove,
337 # 'add': action_add,
338 # 'change': None,
339 # }
340
341 # parser = ArgumentParser(__doc__)
342 # parser.add_argument('--id', '-i',
343 # metavar='ID',
344 # type=int,
345 # help='Select user id')
346 # parser.add_argument('--username', '--user', '-u',
347 # metavar='ID',
348 # help='Select username')
349 # parser.add_argument('--sub',
350 # metavar='ID',
351 # type=int,
352 # help='Specify subscription ID for other options')
353 # parser.add_argument('--name',
354 # metavar='NAME',
355 # help='Set email receiver name')
356 # parser.add_argument('--address', '--email',
357 # metavar='EMAIL',
358 # help='Set email receiver email address')
359 # parser.add_argument('--name-filter', '--filter')
360 # parser.add_argument('--scid-filter', '--scid')
361 # parser.add_argument('--sub-type', '--type')
362 # parser.add_argument('action',
363 # choices=actions)
364
365 # args = parser.parse_args()
366
367 # if args.rec is not None and db.query(
368 # "SELECT count(*) FROM email_receivers WHERE id=:rec", rec=args.rec).fetchone()[0] == 0:
369
370 # parser.error('Receiver {rec} does not exist'.format(rec=args.rec))
371
372 # actions[args.action](args)