forked from erh/mailtools
/
jira_summarizer.py
326 lines (240 loc) · 8.54 KB
/
jira_summarizer.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
import datetime
import dateutil.parser
import getpass
import gmail
import keyring
import os
import pprint
import sys
import time
import myjira
imapHost = "imap.gmail.com"
imapUser = "eliot@10gen.com"
jiraHost = "jira.mongodb.org"
jiraUser = "eliot"
def getPassword( server , account ):
pwd = keyring.get_password( server , account )
if pwd and len(pwd) > 0 :
return pwd
try:
import mypwd
if server == jiraHost and "jira" in dir(mypwd):
return mypwd.jira
if "servers" in dir(mypwd):
if server in mypwd.servers:
s = mypwd.servers[server]
if account in s:
return s[account]
except:
pass
print( "enter password for %s@%s" % ( account, server ) )
pwd = getpass.getpass()
try:
keyring.set_password( server , account , pwd )
except Exception,e:
print( "can't save password: %s" % str(e) )
return pwd
j = myjira.JiraRest( jiraUser , getPassword( jiraHost , jiraUser ) )
hoursBack = 1
def search( query ):
return j.fetch( "search", jql=query, fields="*all", expand="changelog", maxResults=1000 )
def getUpdated():
return search( "project=SERVER AND updated >= -%sh" % hoursBack )
def happendInTimeWindow( dateString ):
parsed = dateutil.parser.parse( dateString )
now = datetime.datetime.utcnow()
now = now.replace(tzinfo=parsed.tzinfo)
diff = now-parsed
return diff.total_seconds() < (hoursBack*3600)
# { "created" : [ ] , "resolved" : [ ] }
categories = {}
def addToCategory( cat, issue ):
if cat not in categories:
categories[cat] = []
categories[cat].append( issue )
def removeIssuesForCategory( cat ):
if cat not in categories:
return []
toreturn = categories[cat]
del categories[cat]
return toreturn
def findCategory( issue ):
fields = issue["fields"]
if happendInTimeWindow( fields["created"] ):
return "created"
if fields["watches"]["isWatching"]:
return "watching"
for change in issue["changelog"]["histories"]:
if not happendInTimeWindow( change["created"] ):
continue
return "modified"
for comment in fields["comment"]["comments"]:
if happendInTimeWindow( comment["created"] ):
return "commented"
for comment in fields["comment"]["comments"]:
if happendInTimeWindow( comment["updated"] ):
return "comment edited"
return "unknown"
def person( p ):
if not p:
return "NONE"
if p["name"] == ["emailAddress"]:
return p["name"]
return p["name"] + "/" + p["emailAddress"]
def issueString( issue ):
fields = issue["fields"]
def prefix( howMany=1):
return " " * howMany
def getPrettyString( howMany, theString ):
big = ""
lines = theString.split( "\n" )
trimmed = False
if len(lines) > 5:
trimmed = True
lines = lines[0:5]
for x in lines:
big = big + prefix(howMany) + x + "\n"
if trimmed:
big = big + prefix(howMany) + "****snipped****\n"
return big
s = issue["key"] + " " + fields["summary"] + "\n"
s = s + prefix() + "https://jira.mongodb.org/browse/" + issue["key"] + "\n"
def printField( name, stringer ):
if name not in fields:
return
return "%s%s: %s\n" % ( prefix(), name, stringer( fields[name] ) )
s = s + printField( "status", lambda x: x["name"] )
s = s + printField( "reporter", person )
s = s + printField( "assignee", person )
s = s + printField( "fixVersions", lambda x: ",".join( map( lambda y: str(y["name"]), x ) ) )
s = s + printField( "priority", lambda x: x["name"] )
s = s + printField( "components", lambda x: ",".join( map( lambda y: str(y["name"]), x ) ) )
firstChange = True
for change in issue["changelog"]["histories"]:
if not happendInTimeWindow( change["created"] ):
continue
if firstChange:
s = s + prefix() + "changes\n"
firstChange = False
s = s + prefix(2) + person( change["author"] ) + "\n"
for item in change["items"]:
s = s + prefix(3) + item["field"] + "\n"
if item["toString"]:
s = s + getPrettyString( 4, item["toString"] )
firstComments = True
for comment in fields["comment"]["comments"]:
created = comment["created"]
updated = comment["updated"]
if not happendInTimeWindow( updated ):
continue
if firstComments:
s = s + prefix() + "comments:\n"
firstComments = False
s = s + prefix(2) + "by: " + person( comment["author"] ) + "\n"
if created != updated:
s = s + prefix(2) + "modified by: " + person( comment["updateAuthor"] ) + "\n"
s = s + getPrettyString( 3, comment["body"] )
return s
def issuesString( name, issues ):
s = "**" + name.upper() + "**\n\n"
for x in issues:
s = s + issueString(x) + "\n"
return s + "\n"
def getText():
updated = getUpdated()
allIssues = updated["issues"]
if len(allIssues) == 0:
return ""
for issue in allIssues:
addToCategory( findCategory( issue ), issue )
fullString = ""
fullString = fullString + issuesString( "created", removeIssuesForCategory( "created" ) )
fullString = fullString + issuesString( "modified", removeIssuesForCategory( "modified" ) )
fullString = fullString + issuesString( "comment added", removeIssuesForCategory( "commented" ) )
watching = removeIssuesForCategory( "watching" )
for x in categories:
fullString = fullString + issuesString( x, categories[x] )
fullString = fullString + "below supressed since should have gotten email\n"
for x in watching:
fullString = "%s%s - %s\n" % ( fullString, x["key"], x["fields"]["summary"] )
return fullString
def findOldestInInbox():
import mailutil
m = mailutil.imapclient( imapHost, imapUser, cache=True, pwd=getPassword( imapHost, imapUser ) )
m.select( "INBOX" , False )
last_seen = time.time()
l = m.list()
oldUIDs = []
mostBack = 0
done = 0
for uid in l:
done = done + 1
msg = m.fetch( uid , True )
m.get_cache().update( { "_id" : m.get_id( uid ) },
{ "$set" : { "lastSeen" : last_seen } } )
headers = msg["headers"]
if not headers:
continue
who = headers["from"]
subject = headers["subject"]
if not subject.startswith( "jira summary @" ):
continue
pcs = subject.split( "@" )
if len(pcs) != 3:
raise Exception( "bad subject [%s]" % subject )
hoursFromSubject = 1 + int(pcs[1].strip())
thing = dateutil.parser.parse( pcs[2].strip() )
now = datetime.datetime.utcnow()
diff = now-thing
hours = int(diff.total_seconds() / 3600)
oldUIDs.append( uid )
if hours > mostBack:
mostBack = hours
if hoursFromSubject > mostBack:
mostBack = hoursFromSubject
return mostBack,oldUIDs
def archiveOldMail( uids ):
if len(uids) == 0:
return
import mailutil
m = mailutil.imapclient( imapHost, imapUser, cache=True, pwd=getPassword( imapHost, imapUser ) )
m.select( "INBOX" , False )
for uid in uids:
m.archive( uid )
m.expunge()
if __name__=="__main__":
sendEmail = True
checkInbox = False
for x in sys.argv[1:]:
if x == "--debug":
sendEmail = False
continue
if x.startswith( "--hours=" ):
hoursBack = int(x.partition("=")[2])
continue
if x == "--inbox":
checkInbox = True
continue
raise Exception( "unknown option: " + x )
allBadUIDs = []
if checkInbox:
try:
mailHoursBack,allBadUIDs = findOldestInInbox()
if mailHoursBack > hoursBack:
hoursBack = mailHoursBack
except Exception,e:
print( "couldn't check inbox: " + str(e) )
text = getText()
if text == "":
sys.exit(0)
if sendEmail:
import mypwd
gmail.send_message( "eliot@mongodb.com",
"jira summary @ %s @ %s" % ( hoursBack, str(datetime.datetime.utcnow() ) ),
text,
smtpPass=mypwd.pwd,
smtpNiceName="Eliot Jira Bot")
if len(allBadUIDs) > 0:
archiveOldMail( allBadUIDs )
else:
print( text )