-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail2muttalias.py
executable file
·493 lines (402 loc) · 14.6 KB
/
mail2muttalias.py
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#!/usr/bin/env python
# RELEASE 0.5
##
# Needs python 1.5 and cursesmodule 1.4 by [email protected] (Oliver Andrich)
# available somewhere on http://www.python.org or directly from
# http://andrich.net/python/selfmade.html
#
# Copyright by Moritz Moeller-Herrmann <[email protected]>
#
# Homepage (check for changes before reporting a bug)
# http://webrum.uni-mannheim.de/jura/moritz/mail2muttalias.html
#
# Use this any way you want. Please inform me of any error/improvement
# and leave the copyright notice untouched.
# No warranties, as this is my first program :-)
# Works for me on Linux with Python 1.5+
#
# Thanks to Josh Hildebrand for some improvements
##
## INSTRUCTIONS
# This script reads all mail adresses from a piped mailfile and
# offers to write them to the specified ALIASFILE below
# append the following lines or similiar to your muttrc(without #!):
#
# macro pager A |'path to script'/aladalcurm.py\n
# source 'path to ALIASFILE specified below"
#
# Then press A if you want to add an adress to your milefile
##
##**** User CONFIGURATION here: *******
# Warning: This file should NOT be your .muttc
# as everything but aliasses are deleted!!
# uncomment and adapt the following line
#
ALIASFILE="/home/miner/.aliases"
#
#
# You may also specify environment variable MUTTALIASFILE
# (only tested if not specified above)
#
# File may be empty, but must exist. Create an empty file witch e.g.
# 'touch filenameyouwant'
##*************************************
# Known bugs:
# If name containing @ is quoted("") before a mail adress,
# the program will not catch the whole name,
# but who would alias such an idiot?
# If you get a problem with "unknown variable / keyword error"
# with KEYUP and KEYDOWN, either get a newer pythoncurses module
# or change them to lowercase.
#
# Probably some more, mail me if you find one!
import re
import string, sys, os
import curses, traceback
try :
testcurses = curses.KEY_UP
except NameError:
print "Your pythoncurses module is old. Please upgrade to 1.4 or higher."
print "Alternative: Modify the script. Change all 6 occurences of curses.KEY_UP"
print "and similiar to lowercase."
try : testAF = ALIASFILE #test if ALIASFILE was configured in script
except NameError:
try: ALIASFILE=os.environ["MUTTALIASFILE"] #test is environment MUTTALIASFILE was set
except KeyError:
print "Please specify ALIASFILE at beginning of script \nor set environment variable MUTTALIASFILE"
print "Aborting ..."
sys.exit()
###Thanks for the following go to Michael P. Reilly
if not sys.stdin.isatty(): # is it not attached to a terminal?
file = sys.stdin.read()
sys.stdin = _dev_tty = open('/dev/tty', 'w+')
# close the file descriptor for stdin thru the posix module
os.close(0)
# now we duplicate the opened _dev_tty file at file descriptor 0 (fd0)
# really, dup creates the duplicate at the lowest numbered, closed file
# descriptor, but since we just closed fd0, we know we will dup to fd0
os.dup(_dev_tty.fileno()) # on UNIX, the fileno() method returns the
# file object's file descriptor
else: # is a terminal
print "Please use as a pipe!"
print "Aborting..."
sys.exit()
# now standard input points to the terminal again, at the C level, not just
# at the Python level.
print "Looking for mail adresses, this may take a while..."
#### define functions
class screenC:
"Class to create a simple to use menu using curses"
def __init__(self):
import curses, traceback
self.MAXSECT = 0
self.LSECT = 1
# Initialize curses
self.stdscr=curses.initscr()
# Turn off echoing of keys, and enter cbreak mode,
# where no buffering is performed on keyboard input
curses.noecho()
curses.cbreak()
# In keypad mode, escape sequences for special keys
# (like the cursor keys) will be interpreted and
# a special value like curses.KEY_LEFT will be returned
self.stdscr.keypad(1)
def titel(self,TITEL="Title - test",HELP="Use up and down arrows + Return"):
"Draws Title and Instructions"
self.stdscr.addstr(0,0,TITEL,curses.A_UNDERLINE) # Title + Help
self.stdscr.addstr(self.Y -2 ,0,HELP,curses.A_REVERSE)
def refresh(self):
self.stdscr.refresh()
def size(self):
"Returns screen size and cursor position"
#Y, X = 0, 0
self.Y, self.X = self.stdscr.getmaxyx()
#self.y, self.x = 0, 0
self.y, self.x = self.stdscr.getyx()
#print Y, X
return self.Y, self.X, self.y, self.x
def showlist(self,LISTE,LSECT=1):
"Analyzes list, calculates screen, draws current part of list on screen "
s = self.Y -3 #space on screen
self.MAXSECT=1
while len(LISTE) > self.MAXSECT * s : # how many times do we need the screen?
self.MAXSECT = self.MAXSECT +1
if self.LSECT > self.MAXSECT: #check for end of list
self.LSECT = LSECT -1
if self.LSECT <= 0: #
self.LSECT =1
if len(LISTE) <= s:
self.LISTPART=LISTE
else :
self.LISTPART=LISTE[s * ( self.LSECT -1 ) : s * self.LSECT ] # part of the List is shown
self.stdscr.addstr(self.Y -2, self.X -len(`self.LSECT`+`self.MAXSECT`) -5, "(" + `self.LSECT` + "/" + `self.MAXSECT` + ")")
#if len(LISTE) > self.Y - 3:
# return 1
for i in range (1, self.Y -2): # clear screen between title and help text
self.stdscr.move(i , 0)
self.stdscr.clrtoeol()
for i in range (0,len(self.LISTPART)): # print out current part of list
Item = self.LISTPART[i]
self.stdscr.addstr(i +1, 0, Item[:self.X])
def getresult(self,HOEHE):
"Get Result from cursor position"
RESULT= self.LISTPART[(HOEHE -1)]
return RESULT
def showresult(self, HOEHE, DICT={}):
"Look up result to show in dictionary if provided, return list member otherwise"
if DICT=={}:
return self.getresult(HOEHE)
else :
return string.join(DICT[self.getresult(HOEHE)], " || ")
def menucall(self, LISTE, DICT={}, TITEL="",HELP="Use up and down arrows, Return to select"):
"Takes a list and offers a menu where you can choose one item, optionally, look up result in dictionary if provided"
REFY=1
self.__init__()
self.size()
self.titel(TITEL,HELP)
self.showlist(LISTE)
self.refresh()
self.stdscr.move(1,0)
while 1: # read Key events
c = self.stdscr.getch()
self.size()
#if c == curses.KEY_LEFT and self.x > 0:
# self.stdscr.move(self.y, self.x -1); REFY = 1 # REFY == refresh: yes
#if c == curses.KEY_RIGHT and self.x < self.X -1:
# #if x < 4 and LENGTH - ZAHLY > y - 1:
# self.stdscr.move(self.y, self.x + 1); REFY = 1
if c == curses.KEY_UP or c == 107: #up arrow or k
if self.y > 1:
self.stdscr.move(self.y -1, self.x); REFY = 1
else :
self.LSECT=self.LSECT-1
self.showlist(LISTE,self.LSECT)
self.stdscr.move(len(self.LISTPART), 0)
REFY = 1
if c == curses.KEY_DOWN or c == 106: #down arrow or j
if self.y < len(self.LISTPART) :
self.stdscr.move(self.y +1, self.x); REFY = 1
else :
self.LSECT=self.LSECT+1
self.showlist(LISTE,self.LSECT)
self.stdscr.move(1,0)
REFY = 1
if c == curses.KEY_PPAGE:
self.LSECT=self.LSECT-1
self.showlist(LISTE,self.LSECT)
self.stdscr.move(1, 0)
REFY = 1
if c == curses.KEY_NPAGE:
self.LSECT=self.LSECT+1
self.showlist(LISTE,self.LSECT)
self.stdscr.move(1,0)
REFY = 1
if c == curses.KEY_END:
self.LSECT=self.MAXSECT
self.showlist(LISTE,self.LSECT)
self.stdscr.move(1,0)
REFY = 1
if c == curses.KEY_HOME:
self.LSECT=1
self.showlist(LISTE,self.LSECT)
self.stdscr.move(1,0)
REFY = 1
if c == 10 : # \n (new line)
ERG = self.getresult(self.y )
self.end()
return ERG
if c == 113 or c == 81: # "q or Q"
self.printoutnwait("Aborted by user!")
self.end()
sys.exit()
return 0
if REFY == 1:
REFY = 0
self.size()
self.stdscr.move(self.Y -1, 0)
self.stdscr.clrtoeol()
self.stdscr.addstr(self.Y -1, 0, self.showresult(self.y,DICT)[:self.X -1 ], curses.A_BOLD)
self.stdscr.move(self.y, self.x)
self.refresh()
def end(self):
"Return terminal"
# In the event of an error, restore the terminal
# to a sane state.
self.Y, self.X, self.y, self.x = 0, 0, 0, 0
self.LISTPART=[]
self.stdscr.keypad(0)
curses.echo()
curses.nocbreak()
curses.endwin()
#traceback.print_exc()
def input(self, promptstr):
"raw_input equivalent in curses, asks for Input and returns it"
self.size()
curses.echo()
self.stdscr.move(0,0)
self.stdscr.clear()
self.stdscr.addstr(promptstr)
self.refresh()
INPUT=self.stdscr.getstr()
curses.noecho()
return INPUT
def printoutnwait(self, promptstr):
"Print out Text, wait for key"
curses.noecho()
self.stdscr.move(0,0)
self.stdscr.clear()
# The new Mutt client pauses after running the script already. No reason
# to pause twice. -Josh
# self.stdscr.addstr(promptstr+"\n\n(press key)")
# self.refresh()
# c = self.stdscr.getch()# read Key events
def analyzealiasfile(ALIASFILE):
"Looks at a mutt aliasfile, returns a list of aliasses and of mail adresses"
try: f=open(ALIASFILE, "r")
except IOError:
print "The file for aliasses you specified,\n","'" + ALIASFILE + "'", "was not found or could not be read.\nAborting ..."
sys.exit()
Aliasline= " "
AL_Adlist=[]
AL_Namlist=[]
while Aliasline != "":
Aliasline=f.readline()
Aliassplit =string.split(Aliasline)
if len(Aliassplit) > 1:
if Aliassplit[0] == "alias":
AL_Namlist.append(Aliassplit[1])
for i in range(len(Aliassplit)):
if "@" in Aliassplit[i]:
Aliasadress = Aliassplit[i]
AL_Adlist.append(Aliasadress)
f.close()
return AL_Adlist, AL_Namlist
def listrex (str, rgx): # Return a list of all regexes matched in string
"Search string for all occurences of regex and return a list of them."
result = []
start = 0 # set counter to zero
ende =len (str) #set end position
suchadress = re.compile(rgx,re.LOCALE)#compile regular expression, with LOCALE
while 1:
einzelerg = suchadress.search(str, start,ende) #create Match Object einzelerg
if einzelerg == None:#until none is found
break
result.append(einzelerg.group()) #add to result
start = einzelerg.end()
return result
def strrex (str): # Return first occurence of regular exp as string
"Search string for first occurence of regular expression and return it"
muster = re.compile(r"<?[\w\b.ßüöä-]+\@[\w.-]+>?", re.LOCALE) #compile re
matobj = muster.search(str) #get Match Objekt from string
if muster.search(str) == None: #if none found
return ""
return matobj.group() #return string
def stripempty (str):#Looks for all empty charcters and replaces them with a space
"Looks for all empty charcters and replaces them with a space,kills trailing"
p = re.compile( "\s+") #shorten
shrt = p.sub(" ", str)
q = re.compile("^\s+|\s+$") #strip
strp = q.sub("", shrt)
return strp
def getmailadressfromstring(str):
"Takes str and gets the first word containing @ == mail adress"
StringSplit=string.split(str)
for i in range(len(StringSplit)):
if "@" in StringSplit[i]:
return StringSplit[i]
return None
### main program
ExAlAdr,ExAlNam = analyzealiasfile(ALIASFILE)
OCCLIST = listrex(file, '"?[\s\w\ö\ä\ü\-\ß\_. ]*"?\s*<?[\w+.-]+\@[\w.-]+>?')#get list, RE gets all Email adresses + prepending words
if OCCLIST:
print len(OCCLIST),"possible adresses found!."
else:
print"ERROR, no mails found"
sys.exit()
for i in range(len(OCCLIST)): #strip all whitespaces + trailing from each list member
OCCLIST[i] = string.strip(OCCLIST [i])
OCCDIC={} # Dictionary created to avoid duplicates
for i in range(len(OCCLIST)): # iterate over
d = OCCLIST[i]
Mail = getmailadressfromstring(OCCLIST[i])
#strrex(OCCLIST[i]) #Mailadresse
Schnitt = - len(Mail) #cut off mail adress
Mail = string.replace(Mail, "<", "")#remove <>
Mail = string.replace(Mail, ">", "")
if "<"+Mail+">" in ExAlAdr: continue # remove already aliassed mail adresses
Name = string.replace (stripempty (d[:Schnitt]), '"', '') #leaves name
if not OCCDIC.get(Mail): # if new Emailadress
Liste = [] # create list for names
Liste.append(Name) # append name
OCCDIC[Mail] = Liste # assign list to adress
else :
Liste = OCCDIC[Mail] # otherwise get list
Liste.append(Name) # append name to list of names
OCCDIC[Mail] = Liste # and assign
KEYS = OCCDIC.keys() #iterate over dictionary, sort names
#KEYS are all the adresses
for z in range( len(KEYS) ):
NAMLIST = OCCDIC[KEYS[z]] # Get list of possible names
d = {} # sort out duplicates and
# remove bad names + empty strings from adresses
for x in NAMLIST:
if x in ["", "<"]: continue
d[x]=x
NAMLIST = d.values()
NAMLIST.sort() # sort namelist alphabetically
print z, KEYS[z], "had possible names:", NAMLIST # Debugging output
OCCDIC[KEYS[z]] = NAMLIST #
print "\n"
###sorting
def Comparelength(x, y):
"Compare number of names in OCCDIC, if equal sort alphabetically."
if len(OCCDIC[y]) == len(OCCDIC[x]):
return cmp(x, y)
if len(OCCDIC[y]) < len(OCCDIC[x]):
return -1
else:
return 1
KEYS.sort(Comparelength) # Keys sort
###menu
ScreenObject=screenC() # initialize curses menu
try:
ZIELADRESS = ScreenObject.menucall(KEYS, OCCDIC, "Choose adress to alias")
if OCCDIC[ZIELADRESS]:
LISTNAM=["***ENTER own NAME"] #add option to edit name
LISTNAM= LISTNAM + OCCDIC[ZIELADRESS]
ZIELNAME = ScreenObject.menucall(LISTNAM, {}, ZIELADRESS + " has which of the possible names?")
# empty Dictionary {} means show list member itself, not looked up result
else : ZIELNAME=""
except:
T=ScreenObject.size()
ScreenObject.end()
# traceback.print_exc() # Uncomment for curses debugging info
# print T
sys.exit()
### enter new names/aliases
if ZIELNAME == "***ENTER own NAME" or ZIELNAME == "":
ZIELNAME = ScreenObject.input(`ZIELADRESS` + " = " + `OCCDIC[ZIELADRESS]` + "\n" + `ZIELADRESS` + " gets which name? ")
ALIAS = ScreenObject.input("Alias for " + '"' + ZIELNAME + '" <' + ZIELADRESS +"> ?\n")
if ALIAS in ExAlNam: #sort out existing aliasses
ScreenObject.printoutnwait(ALIAS + " exists already, terminating!")
ScreenObject.end()
sys.exit()
if ALIAS == "":
ScreenObject.printoutnwait("Aborted")
ScreenObject.end()
sys.exit()
WRITEALIAS = "alias " + ALIAS +" " + ZIELNAME + " <" + ZIELADRESS + ">\n"
if ScreenObject.menucall(["Yes","No"], {}, "Write: '" + WRITEALIAS +"'?" , ALIASFILE) == "No" :
ScreenObject.printoutnwait("Aborted")
ScreenObject.end()
sys.exit()
f = open(ALIASFILE, 'r')
ALFILEH=f.readlines()
f.close()
ALFILEH.append(WRITEALIAS) #append new alias
ALFILEH.sort() #sort by alias
f = open(ALIASFILE, "w")
f.writelines(ALFILEH)
f.close()
ScreenObject.printoutnwait("OK,\n" + WRITEALIAS + " was added to "+ ALIASFILE + "\nProgam terminated")
ScreenObject.end()