emaildump.py 18 KB
Newer Older
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
1
2
3
4
5
6
7
8
9
10
from arc.arcpreferences import PreferenceManager as PM
from arctool import ARCTool
from Default.emailfilter import EmailFilterTable, EmailFilterLogicValidator
from PyQt5.QtCore import QUrl, Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import arc.arcclasses as arcclasses
import arc.arcgui as arcgui
import quopri
import re
11
12
import imaplib
import email
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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

class Plugin(arcclasses.Plugin):
	headers = '|'.join(
		['From','Date','Sent','To','Cc','Bcc','Subject','Importance']
	)

	def __init__(self,package):
		super(Plugin,self).__init__(None,package)

		self.__name__ = "emaildump"
		# Required
		self.name = "Email Dump"
		self.authors = ["unonu"]
		self.version = (0,0,1)
		self.description="Finds a group of emails and dumps their information."
		self.contexts = ['Date']

		self.emails = []
		self.emailIds = {}
		self.fragments = {}
		self.fetched = False

		self.contextFilters = []

		self.igHeader = False
38
		self.addHeader = False
39
		self.igPles = False
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
		self.igReplies= False
		self.igDup 	  = False
		self.igFirstDup = False
		self.igImages = False
		self.igFormat = False
		self.igSpace = False

		self.delim = ''

	#needed
	def setupUi(self):
		#Filter
		self.widget.emailFilterTable = EmailFilterTable()
		self.widget.emailFilterTable.tableChanged.connect(
54
55
56
57
			lambda x: self.widget.fetchButton.setProperty('enabled',
				(x > 0
				or self.widget.contextCheck.isChecked()
				or self.widget.selectEdit.text() != ''))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
		)
		self.widget.emailFilterTable.tableChanged.connect(
				ARCTool.signalProfileChanged
		)

		self.widget.tableLayout.addWidget(self.widget.emailFilterTable)
		self.widget.fetchButton.clicked.connect(self.makeRequest)
		self.widget.logicBox.setValidator(EmailFilterLogicValidator())
		self.widget.selectEdit.textChanged.connect(
			lambda x: self.widget.fetchButton.setEnabled(
				x != '' or len(self.widget.emailFilterTable) > 0
			)
		)

		#Options
		self.widget.contextCheck.stateChanged.connect(
			lambda x : self.widget.fetchButton.setEnabled(x > 0)
		)
76
77
78
		self.widget.infoCheck.stateChanged.connect(
			lambda x: self.setAddHeader(x > 0)
		)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
79
80
81
		self.widget.headerCheck.stateChanged.connect(
			lambda x: self.setIgHeader(x > 0)
		)
82
83
84
		self.widget.plesCheck.stateChanged.connect(
			lambda x: self.setIgPles(x > 0)
		)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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
		self.widget.quoteCheck.stateChanged.connect(
			lambda x: self.setIgReplies(x > 0)
		)
		self.widget.dupCheck.stateChanged.connect(
			lambda x: self.setIgDup(x > 0)
		)
		self.widget.firstCheck.stateChanged.connect(
			lambda x: self.setIgFirstDup(x > 0)
		)
		self.widget.imageCheck.stateChanged.connect(
			lambda x: self.setIgImages(x > 0)
		)
		self.widget.formatCheck.stateChanged.connect(
			lambda x: self.setIgFormat(x > 0)
		)
		self.widget.spaceCheck.stateChanged.connect(
			lambda x: self.setIgSpace(x > 0)
		)
		self.widget.delimeterEdit.textChanged.connect(
			lambda: self.updateDelim()
		)
		self.widget.dupCheck.stateChanged.connect(
			lambda x: self.widget.dupWidget.setEnabled(x > 0)
		)
		self.widget.dupStrength.valueChanged.connect(
			lambda x: self.widget.dupLabel.setText('%d Words' %(x))
		)

	#call super
	def update(self):
		super(Plugin,self).update()

		#updated from extras
		if 'filters' in self.extras:
			self.widget.emailFilterTable.fromSerial(self.extras['filters'])

	#needed
	def storeOptions(self):
		self.options['logicBox'] =\
			(self.widget.logicBox.text(),'text')
		self.options['selectEdit'] =\
126
			(self.widget.selectEdit.text(),'text')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
127
128
129
130
		self.options['delimeterEdit'] =\
			(self.widget.delimeterEdit.text(), 'text')
		self.options['contextCheck'] =\
			(self.widget.contextCheck.isChecked(), 'checked')
131
132
		self.options['infoCheck'] =\
			(self.widget.infoCheck.isChecked(), 'checked')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
133
134
		self.options['headerCheck'] =\
			(self.widget.headerCheck.isChecked(), 'checked')
135
136
		self.options['plesCheck'] =\
			(self.widget.plesCheck.isChecked(), 'checked')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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
		self.options['quoteCheck'] =\
			(self.widget.quoteCheck.isChecked(), 'checked')
		self.options['dupCheck'] =\
			(self.widget.dupCheck.isChecked(), 'checked')
		self.options['firstCheck'] =\
			(self.widget.dupCheck.isChecked(), 'checked')
		self.options['imageCheck'] =\
			(self.widget.imageCheck.isChecked(), 'checked')
		self.options['formatCheck'] =\
			(self.widget.formatCheck.isChecked(), 'checked')
		self.options['spaceCheck'] =\
			(self.widget.spaceCheck.isChecked(), 'checked')
		self.options['dupStrength'] =\
			(self.widget.dupStrength.value(), 'value')

		self.extras['filters'] = self.widget.emailFilterTable.serialize()

	#override
	def generate(self):
		if not self.fetched:
			r = self.makeRequest()
			if r < 0:
				return None

		doc = QTextDocument()
		cursor = QTextCursor(doc)

164
165
166
		# For add headers
		headers = []

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
167
168
169
170
171
172
173
174
175
176
177
178
		_c = _b = None
		for message in self.emails:
			_c = cursor.charFormat()
			_b = cursor.blockFormat()
			text = ''
			for part in message.walk():
				typ = part.get_content_type()
				dis = part.get('Content-Disposition')
				if dis != 'attachment':
					if typ == 'text/plain':
						try:
							text = ('<p>'
179
180
181
								+ re.sub(r'(?<=\r)\n',r'<br/>',
								part.get_payload(decode=True).decode('utf-8'))
								+ '</p>'
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
182
183
184
185
186
187
							)
						except UnicodeDecodeError:
							print("Couldn't decode this part")
							continue
					elif typ == 'text/html':
						try:
188
							text = part.get_payload(decode=True) \
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
189
190
191
192
								.decode('utf-8')
						except UnicodeDecodeError:
							print("Couldn't decode this part")
							continue
193
					elif 'image/' in typ and self.igImages is not True:
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
194
195
196
197
198
199
200
201
202
203
204
205
206
						# Embed image
						# print('embed image')
						dis = dis.split(';',1)
						# print(part.get('Content-ID'))
						# print(dis[1])
						if dis[0] == 'inline':
							img = QImage()
							img.loadFromData(part.get_payload(decode=True))
							doc.addResource(
								doc.ImageResource,
								QUrl('cid:'+part.get('Content-ID')[1:-1]),
								img
							)
207
			# print('message converted')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
208
209
			if self.igReplies:
				text = self.stripReplies(message,text)
210
211
			# if self.igPles:
			# 	text = self.stripPleasantries(text)
212
			# print('replies ignored')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
213
214
			if self.igHeader:
				text = self.stripHeaders(message,text)
215
			# print('header ignored')
216
217
218
219
			if self.addHeader:
				cursor.insertHtml('<br/><p id=29>' + chr(29) + '</p>')
				headers.append(self.getHeader(message))
			# print('custom header added')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
220
221
			cursor.insertHtml(text)
			if self.delim != '':
222
				cursor.insertHtml('<br/><p>' + chr(26) + '</p><br/><br/>')
223
			# print('message inserted')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
224
225
226
227
228
229
230
231
232
233
			cursor.insertBlock()
			cursor.setCharFormat(_c)
			cursor.setBlockFormat(_b)

		if self.igFormat:
			cursor.select(cursor.Document)
			cursor.setCharFormat(_c)
			cursor.setBlockFormat(_b)
		if self.igImages:
			doc.setHtml(self.stripImages(doc.toHtml()))
234
			# print('images stripped')
235

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
236
237
		if self.igDup:
			doc.setHtml(self.stripDuplicate(doc.toHtml()))
238
			# print('duplicates stripped')
239
		# Delimiter (before ples strip in case we accdntly lose a marker)
240
241
242
243
244
245
		doc.setHtml(doc.toHtml().replace(chr(26),self.delim))
		if self.addHeader:
			text = doc.toHtml()
			for h in headers:
				text = text.replace(chr(29),h,1)
			doc.setHtml(text)
246
		if self.igPles:
247
248
			# This isn't in a function because it works on the QTextDoc
			# doc.setHtml(self.stripPleasantries(doc.toHtml()))
249
			plc = QTextCursor(doc)
250
251
			go = True
			while go:
252
253
				plc.movePosition(plc.EndOfBlock,plc.KeepAnchor)
				text = plc.selectedText()
254
255
256
257
258
259
260
261
				words = [w for w in re.split(r'\s',text) if w != '']
				# Removes things that aren't lists or tables or links
				if (len(words) <= 4 and plc.currentList() is None
					and plc.currentTable() is None
					and text != self.delim
					and not re.search('https?://',text)
					and not re.search('(^|\s).\)\s',text)):
					# print(text)
262
					plc.removeSelectedText()
263
				go = plc.movePosition(plc.NextBlock)
264
			# print('pleasantries forgone')
265
266
		print(doc.toHtml().count(chr(29)))

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
267

268
269
		if self.igSpace:
			doc.setHtml(self.collapseSpace(doc.toHtml()))
270
			# print('whitespace stripped')
271

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
		# print("generated")
		return doc

	def makeRequest(self):
		# make async? or at least talk to the user

		# Logic
		req, r, i = self.widget.emailFilterTable.getRequest(
			self.widget.logicBox.text()
		)

		if not req and r == 2:
			ARCTool.getStatusBar().showMessage(
				"Couldn't find filter label '%s'" %(i)
			)
			self.widget.logicBox.setSelection(
				self.widget.logicBox.text().find(i),len(i)
			)
			return -1

292
293
294
		if req == '':
			req = 'ALL'

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
		# Context
		if self.widget.contextCheck.isChecked():
			b = ARCTool.getContext().getBegin("d-MMM-yyyy")
			e = ARCTool.getContext().getEnd()
			if b:
				req += ' SINCE %s' %(b)
			if e:
				e = e.addDays(1)
				e = e.toString("d-MMM-yyyy")
				req += ' BEFORE %s' %(e)


		protocol = imaplib.IMAP4_SSL if PM.getPreference('Default Package',
														 'emailssl')\
									 else imaplib.IMAP4

		with protocol(
			PM.getPreference('Default Package','emailserver'),
313
			int(PM.getPreference('Default Package','emailport') or 993)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
314
315
316
317
318
		) as M:
		
			passDialog = arcgui.LoginDialog(self.widget)
			try:
				passDialog.credentials.connect(
319
					lambda x, y: M.login(x,y) if not(x==y=='') else print('')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
320
				)
321
				passDialog.exec()
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
322
323
			except:
				ARCTool.getStatusBar().showMessage(
324
					"Couldn't login to IMAP server.", 5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
325
326
327
328
329
				)
				return -1

			try:
				ARCTool.getStatusBar().showMessage(
330
					"Selecting mailbox..."
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
331
332
				)
				mailbox = self.widget.selectEdit.text()
333
				mailbox = re.sub(r'(["])',r'\\\g<0>',mailbox)
334
335
				if ((mailbox == '' or mailbox.lower() =='inbox')
					and req == 'ALL'):
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
336
					ARCTool.getStatusBar().showMessage(
337
338
						"Can't select Inbox without at least one filter.",
						5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
339
340
					)
					return -1
341
342
				M.select('"'+mailbox+'"' if mailbox != '' else 'INBOX',
					readonly=True)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
343
344
				try:
					ARCTool.getStatusBar().showMessage(
345
346
347
						"Searching %s..." %(
							mailbox if mailbox != '' else 'Inbox'
						)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
348
349
350
351
					)
					typ, data = M.search(None, req)
				except protocol.error as e:
					ARCTool.getStatusBar().showMessage(
352
						"Couldn't search mailbox: "+str(e), 5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
353
354
355
					)
				else:
					ARCTool.getStatusBar().showMessage(
356
						"Fetching Messages..."
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
357
358
					)
					self.emails = []
359
360
361
362
363
364
					_ = 1
					nums = data[0].split()
					for num in nums:
						ARCTool.getStatusBar().showMessage(
							"Fetching Message %d of %d..." %(_,len(nums))
						)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
365
366
367
368
369
370
371
						typ, data = M.fetch(num, '(RFC822)')
						self.emails.append(
							email.message_from_bytes(data[0][1])
						)
						id = self.emails[-1].get('Message-ID')
						if id:
							self.emailIds[id] = self.emails[-1]
372
						_ +=1
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
373
374
375
					M.close()
			except protocol.error as e:
				ARCTool.getStatusBar().showMessage(
376
					"Couldn't select mailbox: "+str(e), 5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
377
378
379
380
381
382
				)
				return -1

		ARCTool.getStatusBar().showMessage(
			"Fetched %d message%s" %(len(self.emails),
				'' if len(self.emails) == 1 else 's'
383
384
			),
			5000
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
385
386
387
388
		)
		self.fetched = True
		return 0

389
390
391
	def setAddHeader(self, b):
		self.addHeader = b

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
392
393
394
	def setIgHeader(self, b):
		self.igHeader = b

395
396
397
	def setIgPles(self, b):
		self.igPles = b

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
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
	def setIgReplies(self, b):
		self.igReplies = b

	def setIgDup(self, b):
		self.igDup = b

	def setIgFirstDup(self, b):
		self.igFirstDup = b

	def setIgImages(self, b):
		self.igImages = b

	def setIgFormat(self, b):
		self.igFormat = b

	def setIgSpace(self, b):
		self.igSpace = b

	def updateDelim(self):
		self.delim = self.widget.delimeterEdit.text()

	def stripHeaders(self,message,text):
		text = re.sub('(?P<p><p )?.*?(?:%s):.+(?(p)[^`]*?</p>)\n?'\
			%(self.headers),'',text)
		return text

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
	def stripPleasantries(self,text):
		return text

		# deltas = []
		# blocks = re.split('<br/?>',text)
		# if len(blocks) == 1:
		# 	return text

		# print('enough blocks')
		# for b in blocks[:]:
		# 	_b = re.sub(r'(?s)\s*<.+?>\s*', '',b)
		# 	_b = re.sub('\xa0',' ',_b)
		# 	_b = re.sub(r'&nbsp;',' ',_b)
		# 	if len(re.split(r'\b',_b)) < 4:
				# blocks.remove(b)
		# print(blocks)
		# return ''.join(blocks)
		# breaks = re.findall('<br/?>',text)
		# blockIndex = [
		# 	len(blocks[x]) + len(breaks[x]) for x in range(len(breaks))
		# ] + [len(blocks[-1])]
		# print('block indicies', blockIndex)
		# for i in range(1,len(blocks)):
		# 	blockIndex[i] += blockIndex[i-1]

		# for b in blocks:
		# 	b = re.sub(r'(?s)\s*<.+?>\s*', '',b)
		
		# wc = len(blocks[0])
		# for i in range(1,len(blocks)):
		# 	deltas.append( abs(len(blocks[i]) - len(blocks[i-1])) )
		# 	wc = len(blocks[i])
		# avg = wc/len(blocks)

		# deltaN = sum(deltas) / (2*wc)
		# blockLens = [len(b) for b in blocks]
		
		# if deltaN > avg/max(blockLens):
		# 	asc = 0
		# 	while deltas[asc] < avg:
		# 		asc += 1
		# 	des = len(deltas) - 1
		# 	# Naive approach, should really check to see if other islands exist
		# 	while des > asc and deltas[des] < avg:
		# 		des -= 1

		# 	print('start/stop block index', asc, des)
		# 	text = text[blockIndex[asc]:blockIndex[des]]
		# return text

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
474
475
476
477
478
479
480
481
482
	def stripImages(self,text):
		text = re.sub('(?s)<img .+?(?:/>|</img>)','',text)
		return text

	def collapseSpace(self,text):
		# Collapse Spaces
		text = re.sub('\xa0',' ',text)
		text = re.sub(' +',' ',text)

483
		# Collapse Breaks/Paragraphs/Spans/Divs
484
485
486
		text = re.sub(r'(?s)<br>\s*(?:</br>)?','<br/>',text)
		text = re.sub(r'(?s)(?<=>)\s*<br\s*/?>\s*(?=<)', '',text)
		text = re.sub(r'(?s)\s*<p( [^>]+)?>\s*</p>\s*','',text)
487
488
489
		text = re.sub(r'(?s)\s*<span( [^>]+)?>\s*</span>\s*','',text)
		text = re.sub(r'(?s)\s*<div( [^>]+)?>\s*</div>\s*','',text)
		text = re.sub(r'(?s)(?<=>)\s*<br\s*/?>\s*(?=<)', '',text) #bandaid
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521

		return text

	def stripReplies(self,message,text):
		ids = message.get("References")
		if ids:
			ids = re.split(',| ',ids)
			ids = [i.strip() for i in ids if i != '']
			# print(ids)
			for id in ids:
				if id in self.emailIds:
					# Remove this previous emails content from me
					ref = ''
					for part in self.emailIds[id].walk():
						typ = part.get_content_type()
						dis = part.get('Content-Disposition')
						if dis != 'attachment':
							if typ == 'text/plain' or typ == 'text/html':
								ref = part.get_payload(decode=True)\
									.decode('utf-8')
					# if self.igHeader:
					# 	ref = self.stripHeaders(self.emailIds[id[-2]],ref)

					bodyText = re.search('(?s)<body[^>]*?>(.+)</body>',text)
					bodyRef = re.search('(?s)<body[^>]*?>(.+)</body>',ref)
					if bodyText and bodyRef:
						bodyText = bodyText.group(1).strip()
						container = text.split(bodyText)
						bodyRef = bodyRef.group(1).strip()
						bodyText = re.sub('\xa0',' ',bodyText)
						bodyRef = re.sub('\xa0',' ',bodyRef)
						bodyTags = re.findall(r'\s*<.+?>\s*',bodyText)
522
						bodyText = re.sub(r'\s*<.+?>\s*',chr(24),bodyText)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
523
524
						bodyRef = [re.escape(p) for p in \
							re.split(r'\s*<.+?>\s*',bodyRef) if p != '']
525
						bodyRef = '(?s)' + (chr(24)+'+').join(bodyRef)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
526
527
528
529
530
						bodyRef = re.sub(r'(\\\s)+',r'\\s+',bodyRef)

						# Search for the original message within the reply
						partial = re.search(bodyRef,bodyText)
						if partial:
531
							excise = partial.group(0).count(chr(24))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
532
533
							offset =\
								bodyText[:bodyText.find(partial.group(0))]\
534
								.count(chr(24))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
535
536
537
538
539
							bodyText = bodyText.replace(partial.group(0),'')
							bodyTags = (bodyTags[:offset]
										+ bodyTags[offset+excise:])
							# Replace the tags
							for t in bodyTags:
540
								bodyText = bodyText.replace(chr(24),t,1)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
541
542
543
544
							text = container[0] + bodyText + container[1]
						# We messed up? Impossible...
						# else:
						# 	print(bodyText)
545
						# 	print('-------vvvvvv-------')
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
546
547
548
						# 	print(bodyRef)
		return text

549
550
551
552
553
554
555
556
557
558
	def getHeader(self, message):
		text = '<br/><span><p style="text-align:center;font-weight:bold;">From '
		# print(message.keys())
		text += message.get('From')
		text += ' on '
		text += message.get('Date')
		text += ':</p></span><br/>'

		return text

Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
559
560
561
562
563
564
	def stripDuplicate(self, text):
		num = self.widget.dupStrength.value()
		globs = {}
		body = re.search('(?s)<body[^>]*?>(.+)</body>',text).group(1)
		container = text.split(body)
		tags = re.findall(r'(?s)\s*<.+?>\s*',body)
565
		# Replace tags
566
		stripped = re.sub(r'(?s)\s*<.+?>\s*',chr(24),body)
567
		# Replace 
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
568
569
		stripped = re.sub('\xa0',' ',stripped)
		stripped = re.sub(r'&nbsp;',' ',stripped)
570
571
572
573
574
		# Uncomment these two file sections to output stripped to files
		# Useful for regex testing
		# f = open('wspace.txt','w')
		# f.write(stripped)
		# f.close()
575
576
		spaces = re.findall(r'(?s)\s+',stripped)
		stripped = re.sub(r'(?s)\s+',r' ',stripped)
577
578
579
580
		# f = open('wospace.txt','w')
		# f.write(stripped)
		# f.close()
		# print("stripped")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
581
		_ = []
582
583
584
585
586
587
		for word in re.finditer(
			# r'(?s)(?:(.+?[\s]+?)(?:\b))|(.+?)$',stripped):
			# r'(?s)(?:(.+?[\s]+))|(.+?)$',stripped):
			# r'(?s)(?:(.+?(?:\s|)+(?=[\w ])))|(.+?)$',stripped):
			r'(?s)(?:(.+?(?:\s|(?:(?![., ])))+))|(.+?)$',stripped):

588
			_.append(
589
590
				(word.group(1),word.start(1),word.end(1)) if word.group(1) else
				(word.group(2),word.start(2),word.end(2))
591
			)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
592
			if len(_) == num:
593
594
595
				hsh = ''.join(x[0].replace(chr(24),'') for x in _)
				hsh = hsh.replace(' ','')
				hsh = hsh.__hash__()
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
596
597
				if hsh not in globs:
					globs[hsh] = []
598
599
600
601
				# else:
					# print('collision',hsh,
					# ''.join(x[0].replace(chr(24),'') for x in _).replace(' ', ''),
					# len(globs[hsh])+1)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
602
603
604
				globs[hsh].append((_[0][1],_[-1][2]))
				_.pop(0)

605
		# print("globbed")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
606
607
608
609
		chains = []
		ranges = []
		for d in globs:
			if len(globs[d]) > 1:
610
				ranges += globs[d][1 if self.igFirstDup else 0:]
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
611
612
613
614
615
		ranges.sort()
		for r in ranges:
			if len(chains) == 0:
				chains.append([r[0],r[1]])
				continue
616
			if r[0] <= chains[-1][1] and r[1] > chains[-1][1]:
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
617
				chains[-1][1] = r[1]
618
			elif r[0] > chains[-1][1]:
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
619
				chains.append([r[0],r[1]])
620
		# print("chained")
621
		# Only remove the text but keep the tags
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
622
		offset = 0
623
		# print('#chains=',len(chains))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
624
625
626
627
628
629
		for c in chains:
			# Could partition, but I want variable names
			chunk = stripped[c[0]-offset:c[1]-offset]
			head = stripped[:c[0]-offset]
			tail = stripped[c[1]-offset:]
			# print(chunk)
630
631
632
			lh, lt = len(head), len(tail)
			# print(lh, lt, lh-lt)

633
			tagsRemoved = chunk.count(chr(24))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
634
635
			spaceRemoved = chunk.count(' ')
			offset += len(chunk) - tagsRemoved
636
637
			spaces = (spaces[:head.count(' ')]
					  + spaces[head.count(' ') + spaceRemoved:])
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
638

639
			stripped = head + chr(24)*tagsRemoved + tail
640
		# print("excised")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
641
642
643
644

		for s in spaces:
			stripped = stripped.replace(' ',s,1)
		for t in tags:
645
			stripped = stripped.replace(chr(24),t,1)
646
		# print("replaced")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
647
648

		return container[0] + stripped + container[1]