emaildump.py 18.1 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
270
271
		if self.igSpace:
			doc.setHtml(self.collapseSpace(doc.toHtml()))
			print('whitespace stripped')

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
324
325
326
327
328
329
			except:
				ARCTool.getStatusBar().showMessage(
					"Couldn't login to IMAP server."
				)
				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
483
	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)

		# Collapse Breaks
484
485
486
487
		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*<span( [^>]+)?>\s*</span>\s*','',text)
		text = re.sub(r'(?s)\s*<p( [^>]+)?>\s*</p>\s*','',text)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
488
489
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

		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)
520
						bodyText = re.sub(r'\s*<.+?>\s*',chr(24),bodyText)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
521
522
						bodyRef = [re.escape(p) for p in \
							re.split(r'\s*<.+?>\s*',bodyRef) if p != '']
523
						bodyRef = '(?s)' + (chr(24)+'+').join(bodyRef)
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
524
525
526
527
528
						bodyRef = re.sub(r'(\\\s)+',r'\\s+',bodyRef)

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

547
548
549
550
551
552
553
554
555
556
	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
557
558
559
560
561
562
	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)
563
		print(len(tags),tags[0])
564
		# Replace tags
565
		stripped = re.sub(r'(?s)\s*<.+?>\s*',chr(24),body)
566
		# Replace 
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
567
568
		stripped = re.sub('\xa0',' ',stripped)
		stripped = re.sub(r'&nbsp;',' ',stripped)
569
570
571
		f = open('wspace.txt','w')
		f.write(stripped)
		f.close()
572
		spaces = re.findall(r'(?s)\s+',stripped)
573
		print(len(spaces),spaces[0])
574
		stripped = re.sub(r'(?s)\s+',r' ',stripped)
575
576
577
		f = open('wospace.txt','w')
		f.write(stripped)
		f.close()
578
		print("stripped")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
579
		_ = []
580
		# for word in re.finditer(r'(?:^| )(.+?)(?:(?= )|$)',stripped):
581
		for word in re.finditer(r'(?s)(?:\b)(.+?\s+?)(?:\b)',stripped):
582
		# for word in re.finditer(r'(?:\s)(.+?)(?:\s)',stripped):
583
584
585
586
587
588
589
590
			_.append(
				(word.group(1),word.start(1),word.end(1))
			)
			if (chr(24) in _[-1][0]
				or re.search(r'[-;:/.,=\\!?@#$%^&*()_+<>\[\]|{}]',_[-1][0])):
				_.pop(-1)
				# print('-> '+_.pop(-1)[0])
				continue
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
591
			if len(_) == num:
592
593
594
595
596
597
				# I think its missing the collision with the dot after the 11
				# I tried removing spaces but that doesnt seem to actually
				# affect the results. At leasts it's vastly improved from b4
				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
598
599
				if hsh not in globs:
					globs[hsh] = []
600
601
				else:
					print('collision',hsh,''.join(x[0].replace(chr(24),'') for x in _),len(globs[hsh]))
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
602
603
				globs[hsh].append((_[0][1],_[-1][2]))
				_.pop(0)
604
605
606
				# print('-> '+_.pop(0)[0])
			# print(_)
			# input()
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
607

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

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

642
			stripped = head + chr(24)*tagsRemoved + tail
643
		print("excised")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
644
645
646
647

		for s in spaces:
			stripped = stripped.replace(' ',s,1)
		for t in tags:
648
			stripped = stripped.replace(chr(24),t,1)
649
		print("replaced")
Cage, Marshall Andrew's avatar
Cage, Marshall Andrew committed
650
651

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