aboutsummaryrefslogtreecommitdiffstats
path: root/pygn2m
diff options
context:
space:
mode:
authorMatěj Cepl <mcepl@cepl.eu>2014-12-21 22:18:48 +0100
committerMatěj Cepl <mcepl@cepl.eu>2014-12-21 22:43:08 +0100
commit52b3df8247561fa138b273efd18e7f03a54880ef (patch)
treedb629d4d90eded920160dbf2c63b80e483fa8a4b /pygn2m
parentaaba562ae6e30c3b8e18938eea58f0a8df73bd57 (diff)
downloadpygn-52b3df8247561fa138b273efd18e7f03a54880ef.tar.gz
switch to argparse in pygn2m
and cleanup in pygn2m, news2mail.py (and some leftovers in pygm2n)
Diffstat (limited to 'pygn2m')
-rwxr-xr-xpygn2m292
1 files changed, 118 insertions, 174 deletions
diff --git a/pygn2m b/pygn2m
index d093756..0b958f1 100755
--- a/pygn2m
+++ b/pygn2m
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-
+# -*- coding: utf-8 -*-
"""News to mail gateway script. Copyright 2000 Cosimo Alfarano
Author: Cosimo Alfarano
@@ -13,202 +13,146 @@ Thanks to md for this useful formula. Beer is beer.
Gets news article from stdin and sends it via SMTP.
"""
-
-import sys, os
-import getopt
-from string import split
+from __future__ import print_function
+import sys
+import os
+import argparse
sys.path.append('/usr/lib/pyg')
import pyginfo
import whitelist
import news2mail
-#import mail2news
-
-
-def parse_cmdline(gw):
- """Parses cmdline with getopt.
- set a dictionary with smtp new header in gw parameter (gw.smtpheads)
- return (test,verbose) boolean tuple
- """
-
- opt, arg = None, None
- test, verbose = 0, 0
- retnull = (None, None)
-
- try:
- opt, arg = getopt.getopt(sys.argv[1:],"H:t:s:e:w:l:hdvVT")
- except (getopt.error), message:
- print '%s: %s\n' % (sys.argv[0], message)
- sys.exit(1)
-
- if len(sys.argv) == 1 or opt == []:
- gw.smtpheads = None
- return retnull
-
- for i in range(len(opt)):
- if opt[i][0] == '-h':
- gw.smtpheads = None
- return retnull
- elif opt[i][0] == '-v':
- gw.smtpheads = None
- return retnull
- elif opt[i][0] == '-H':
- gw.smtpserver = opt[i][1]
- elif opt[i][0] == '-s':
- gw.smtpheads['Resent-Sender:'] = opt[i][1] + '\n'
- gw.sender = opt[i][1]
- elif opt[i][0] == '-t' or opt[i][0] == '-r':
- gw.smtpheads['To:'] = opt[i][1] + '\n'
- gw.rcpt = opt[i][1]
- elif opt[i][0] == '-e':
- gw.smtpheads['Resent-From:'] = opt[i][1] + '\n' #envelope
- gw.envelope = opt[i][1]
- elif opt[i][0] == '-w':
- gw.wlfile = opt[i][1]
- elif opt[i][0] == '-l':
- gw.logfile = opt[i][1]
- elif opt[i][0] == '-d':
- gw.debug = 1
- elif opt[i][0] == '-T':
- test = 1
- elif opt[i][0] == '-V':
- verbose = 1
-
-# By rfc822 [Resent-]Sender: should be ever set, unless == From:
+
+
+def parse_cmdline():
+ """
+ set a dictionary with smtp new header in gw parameter (gw.smtpheads)
+ return (test,verbose) boolean tuple
+ """
+ i = pyginfo.pygsinfo()
+ parser = argparse.ArgumentParser(
+ description='%s version %s - Copyright 2000 Cosimo Alfarano\n%s' %
+ (i.PROGNAME, i.VERSION, i.__doc__))
+
+ parser.add_argument('-H', '--smtpserver', default='')
+ parser.add_argument('-s', '--sender', required=True, default='')
+ parser.add_argument('-e', '--envelope', default='')
+ parser.add_argument('-t', '--to', dest='rcpt', required=True)
+ parser.add_argument('-w', '--wlfile')
+ parser.add_argument('-l', '--logfile')
+
+ # TODO eventually we should refactor these to be Boolean
+ # and use store_true
+ parser.add_argument('-T', '--test',
+ help='test mode (not send article via SMTP)',
+ action='store_true')
+ parser.add_argument('-d', '--debug',
+ action='store_true')
+ parser.add_argument('-V', '--verbose', help='verbose output',
+ action='store_true')
+
+ opts = parser.parse_args()
+
+# By rfc822 [Resent-]Sender: should be ever set, unless == From:
# (not this case). Should be a human, while [Resent-]From: may be a program.
- if gw.rcpt == '' or gw.sender == '':
- print 'missing command line option'
- gw.smtpheads = None
- return retnull
+ if opts.rcpt == '' or opts.sender == '':
+ raise argparse.ArgumentError('missing command line option')
- if gw.envelope == '' and gw.sender != '':
- gw.smtpheads['Resent-From:'] = gw.sender + '\n'
- gw.envelope = gw.sender
- elif gw.envelope == -1:
- gw.smtpheads = None
- return retnull
+ if opts.envelope == '' and opts.sender != '':
+ opts.envelope = opts.sender
- sys.argv[1:] = arg
+ return opts
- return (test, verbose)
+"""main is structured in 4 phases:
+ 1) check and set pyg's internal variables
+ 2) check whitelist for users' permission
+ 3) format rfc 822 headers from input article
+ 4) open smtp connection and send e-mail
+"""
-def usage():
- i = pyginfo.pygsinfo()
+try:
- print '%s version %s - Copyright 2000 Cosimo Alfarano' % (i.PROGNAME, i.VERSION)
- print i.__doc__
- print
- print 'usage: %s [-h] [-d] [-T] [-V] [-H smtphost] [-l logfile] [-w whitelist] -t recipient@... -s sender@... [-e envelope@...]' % split(sys.argv[0],'/')[-1]
- print '-t -s recipient, sender are necessary'
- print '-e envelope [default: same of sender]'
- print '-T for test mode (not send article via SMTP)'
- print '-V for verbose output'
- print '-d for debug'
- print '-h or -v for this info'
-
+ """phase 1:
+ check and set pyg's internal variables
+ """
+ n2m = news2mail.news2mail()
+ owner = None
+ # it returns only test, other parms are set directly in the actual
+ # parameter
+ args = parse_cmdline()
+ # check if n2m has some file prefercences set on commandline
+ if n2m.wlfile is None:
+ wl = os.environ['HOME'] + '/pyg.whitelist'
+ else:
+ wl = n2m.wlfile
+ if n2m.logfile is None:
+ log = os.environ['HOME'] + '/pyg.log'
+ else:
+ log = n2m.logfile
+# print 'using %s %s\n' % (wl,log)
+ wl = whitelist.whitelist(wl, log)
-"""main is structured in 4 phases:
- 1) check and set pyg's internal variables
- 2) check whitelist for users' permission
- 3) format rfc 822 headers from input article
- 4) open smtp connection and send e-mail
-"""
+ # reads stdin and parses article separating head from body
+ n2m.readfile()
+ n2m.parsearticle()
+ """phase 2:
+ check whitelist for user's permission
+ """
-try:
+ # make a first check of From: address
+ owner = wl.checkfrom(n2m.nntpheads['From:'])
+ if owner is None:
+ if sys.stdin.isatty() == 1 or args.test:
+ print ('"%s" is not in whitelist!' % (n2m.nntpheads['From:'][:-1]))
+ else:
+ wl.logmsg(n2m.nntpheads, wl.DENY)
+
+ # if verbose, I want to print out headers, so I can't
+ # exit now.
+ if not args.verbose:
+ sys.exit(1)
+
+ """phase 3:
+ format rfc 822 headers from input article
+ """
+
+ n2m.mergeheads() # make unique dict from NNTP and SMTP dicts
+
+ n2m.addheads() # add some important heads
+ n2m.renameheads() # rename useless heads
+ n2m.removeheads() # remove other heads
+
+ n2m.sortheads() # sort remaining heads :)
+
+ # prints formatted email message only (without send) if user wants
+ if args.verbose:
+ for line in n2m.headers:
+ print(line[:-1])
+
+ if args.owner is None:
+ sys.exit(1)
+
+ """phase 4:
+ open smtp connection and send e-mail
+ """
- """phase 1:
- check and set pyg's internal variables
- """
-
- n2m = news2mail.news2mail()
- owner = None
-
- # it returns only test, other parms are set directly in the actual parameter
- (test, verbose) = parse_cmdline(n2m)
- if (test, verbose) == (None, None):
- usage()
- sys.exit(0)
-
-
- # check if n2m has some file prefercences set on commandline
- if(n2m.wlfile == None):
- wl = os.environ['HOME'] + '/pyg.whitelist'
- else:
- wl = n2m.wlfile
-
- if(n2m.logfile == None):
- log = os.environ['HOME'] + '/pyg.log'
- else:
- log = n2m.logfile
-
-# print 'using %s %s\n' % (wl,log)
-
- wl = whitelist.whitelist(wl,log)
-
- # reads stdin and parses article separating head from body
- n2m.readfile()
- n2m.parsearticle()
-
-
- """phase 2:
- check whitelist for user's permission
- """
-
- # make a first check of From: address
- owner = wl.checkfrom(n2m.nntpheads['From:'])
- if(owner == None):
- if(sys.stdin.isatty()==1 or test):
- print ('"%s" is not in whitelist!' % (n2m.nntpheads['From:'][:-1]))
- else:
- wl.logmsg(n2m.nntpheads,wl.DENY)
-
- # if verbose, I want to print out headers, so I can't
- # exit now.
- if(not verbose):
- sys.exit(1)
-
- """phase 3:
- format rfc 822 headers from input article
- """
-
- n2m.mergeheads() # make unique dict from NNTP and SMTP dicts
-
- n2m.addheads() # add some important heads
- n2m.renameheads() # rename useless heads
- n2m.removeheads() # remove other heads
-
- n2m.sortheads() # sort remaining heads :)
-
- # prints formatted email message only (without send) if user wants
- if(verbose):
- for line in n2m.headers:
- print line[:-1]
-
- if(owner == None):
- sys.exit(1)
-
-
- """phase 4:
- open smtp connection and send e-mail
- """
-
- if len(n2m.headers) > 0:
- wl.logmsg(n2m.heads_dict,wl.ACCEPT,owner)
- if(not test):
- n2m.sendarticle()
- else:
- print 'Error: No Headers!!!'
+ if len(n2m.headers) > 0:
+ wl.logmsg(n2m.heads_dict, wl.ACCEPT, owner)
+ if not args.test:
+ n2m.sendarticle()
+ else:
+ print('Error: No Headers!!!')
except KeyboardInterrupt:
- print 'Keyboard Interrupt'
- sys.exit(1)
+ print('Keyboard Interrupt')
+ sys.exit(1)