#!/usr/bin/env python
# list-people 0.1
# Produce a list of people who've posted to the given newsgroup.
# Usage: list-people.py newsserver group [peoplefile [command]]
# If a third argument is given, list the people who aren't in the
# file named by that argument, then write the list to that file.
# (The file will be silently created if it doesn't already exist.)
# If a fourth argument is given, execute that command with '{}' replaced
# by the mail address of each new person rather than printing their names.
# For instance:
#  list-people.py localhost my.group my.group.list "mail -s Welcome {} <msg"
# - Adam Sampson <ats@offog.org>

import sys
import os
import nntplib
import re
import string

# This regexp should extract a mail address from a From: header.
mailre = re.compile(r"([\w\$\.]+@[-a-z0-9]+\.[-a-z0-9\.]+).*", re.IGNORECASE)

# This regexp should match addresses you're interested in.
interestingre = re.compile(r"^[a-z]+[0-9]+@ukc\.ac\.uk$", re.IGNORECASE)

# Strings in this list will be removed from mail addresses.
removables = [ "nospamplease", "-nospam-", "nospam" ]

err = sys.stderr.write
if len(sys.argv) < 3:
	err("Usage: list-people.py newsserver group [peoplefile]\n")
	sys.exit(20)
try:
	n = nntplib.NNTP(sys.argv[1])
except:
	err("Can't connect to newsserver.\n")
	sys.exit(20)

group = sys.argv[2]
resp, count, first, last, name = n.group(group)
count = string.atoi(count)
resp, senders = n.xhdr("from", first + "-" + last)

posters = {}
for n in range(len(senders)):
	id, sender = senders[n]
	try:
		mailaddr = string.lower(mailre.search(sender).group(1))
	except AttributeError:
		mailaddr = "unknown"
	for x in removables: mailaddr = string.replace(mailaddr, x, "")
	posters[mailaddr] = 1

people = filter(lambda x: interestingre.match(x), posters.keys())
people.sort()

if len(sys.argv) > 3:
	oldfile = sys.argv[3]
	try:
		oldpeople = map(string.strip, open(oldfile).readlines())
	except:
		oldpeople = ""

	posters = {}
	for x in oldpeople: posters[x] = 1
	newpeople = filter(lambda x: not posters.has_key(x), people)

	try:
		f = open(oldfile, "w")
	except:
		err("Can't open " + oldfile + " for writing.\n")
		sys.exit(20)
	for x in newpeople: posters[x] = 1
	for x in posters.keys(): f.write(x + "\n")
	f.close()
	people = newpeople

if len(sys.argv) > 4:
	cmd = sys.argv[4]
	for x in people: os.system(string.replace(cmd, "{}", x))
else:
	for x in people: print x

