-
Notifications
You must be signed in to change notification settings - Fork 6
/
annotations.py
executable file
·553 lines (471 loc) · 20.3 KB
/
annotations.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
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#!/usr/bin/env python
# coding: utf-8
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2013, Greg Riker <[email protected]>'
__docformat__ = 'restructuredtext en'
import hashlib, re
from datetime import datetime
from xml.sax.saxutils import escape
from calibre.devices.usbms.driver import debug_print
from calibre.ebooks.BeautifulSoup import BeautifulSoup, Tag
from calibre_plugins.marvin_manager.common_utils import Logger
from calibre_plugins.marvin_manager.config import plugin_prefs
COLOR_MAP = {
'Blue': {'bg': '#b1ccf3', 'fg': 'black'},
'Default': {'bg': 'transparent', 'fg': 'black'},
'Gray': {'bg': 'LightGray', 'fg': 'black'},
'Green': {'bg': '#c8eb7b', 'fg': 'black'},
'Pink': {'bg': '#f4b0d2', 'fg': 'black'},
'Purple': {'bg': '#d8b0ef', 'fg': 'black'},
'Red': {'bg': 'red', 'fg': 'black'},
'Underline': {'bg': 'transparent', 'fg': 'blue'},
'Yellow': {'bg': '#f4e681', 'fg': 'black'},
}
ANNOTATION_DIV_STYLE = "margin:0 0 0.5em 0"
ANNOTATIONS_HEADER = '''<div class="user_annotations" style="margin:0"></div>'''
ANNOTATIONS_HTML_TEMPLATE = (
'<html xmlns="http://www.w3.org/1999/xhtml">'
'<head>'
'<meta http-equiv="content-type" content="text/html; charset=utf-8"/>'
'<meta name="calibre-dont-sanitize">'
'<title>Annotations</title>'
'<style></style>'
'</head>'
'<body></body>'
'</html>'
)
class Annotation(object):
"""
A single instance of an annotation
"""
div_style = "margin-bottom:1em"
all_fields = [
'description',
'genre',
'hash',
'highlightcolor',
'location',
'location_sort',
'note',
'reader_app',
'text',
'timestamp',
]
def __init__(self, annotation):
for p in self.all_fields:
setattr(self, p, annotation.get(p))
class Annotations(Annotation, Logger):
'''
A collection of Annotation objects
annotations: [{title:, path:, timestamp:, genre:, highlightcolor:, text:} ...]
Inherits Annotation solely to share style characteristics for agroups
'''
@dynamic_property
def annotations(self):
def fget(self):
return self.__annotations
return property(fget=fget)
def __init__(self, opts, title=None, annotations=None, cid=None, genre=None):
self.opts = opts
self.cid = cid
self.title = title
self.genre = genre
self.__annotations = []
if annotations:
self.annotations = annotations
def _annotation_sorter(self, annotation):
'''
Input: [01 Feb 2003 12:34:56 ...
Output (conforming): 2003-02-01-12:34:56
Output (non-conforming): 0
'''
if False:
key = self._timestamp_to_datestr(annotation.timestamp)
MONTHS = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
if not re.match('\d{2} \w{3} \d{4} \d{2}:\d{2}:\d{2}', key):
return "!%s" % key
sts_elems = key[1:-1].split(' ')
year = sts_elems[2]
month = "%02d" % MONTHS.index(sts_elems[1])
day = sts_elems[0]
time = sts_elems[3]
return "%s-%s-%s-%s" % (year, month, day, time)
else:
return annotation.location_sort
def _timestamp_to_datestr(self, timestamp):
'''
Convert timestamp to
01 Jan 2011 12:34:56
'''
from calibre_plugins.marvin_manager.appearance import default_timestamp
d = datetime.fromtimestamp(float(timestamp))
friendly_timestamp_format = plugin_prefs.get('appearance_timestamp_format', default_timestamp)
try:
friendly_timestamp = d.strftime(friendly_timestamp_format)
except:
friendly_timestamp = d.strftime(default_timestamp)
return friendly_timestamp
def create_soup(self):
'''
Create a template <div> for user annotations
'''
return BeautifulSoup(ANNOTATIONS_HEADER)
def to_HTML(self, soup):
'''
Generate HTML with user-specified CSS, element order
Add to passed soup
'''
# Retrieve CSS prefs
from calibre_plugins.marvin_manager.appearance import default_elements
stored_css = plugin_prefs.get('appearance_css', default_elements)
elements = []
for element in stored_css:
elements.append(element['name'])
if element['name'] == 'Note':
note_style = re.sub('\n', '', element['css'])
elif element['name'] == 'Text':
text_style = re.sub('\n', '', element['css'])
elif element['name'] == 'Location':
ts_style = re.sub('\n', '', element['css'])
# Additional CSS for timestamp color and bg to be formatted
datetime_style = ("background-color:{0};color:{1};" + ts_style)
# Order the elements according to stored preferences
comments_body = ''
for element in elements:
if element == 'Text':
comments_body += '{text}'
elif element == 'Note':
comments_body += '{note}'
elif element == 'Location':
ts_css = '''<table class="annotation" style="{ts_style}" color="{color}">
<tr>
<td class="location" style="text-align:left">{location}</td>
<td class="timestamp" uts="{unix_timestamp}" style="text-align:right">{friendly_timestamp}</td>
</tr>
</table>'''
comments_body += re.sub(r'>\s+<', r'><', ts_css)
if self.annotations:
#soup = BeautifulSoup(ANNOTATIONS_HEADER)
dtc = 0
# Add the annotations
for i, agroup in enumerate(sorted(self.annotations, key=self._annotation_sorter)):
location = agroup.location
if location is None:
location = ''
friendly_timestamp = self._timestamp_to_datestr(agroup.timestamp)
text = ''
if agroup.text:
for agt in agroup.text:
text += '<p class="highlight" style="{0}">{1}</p>'.format(text_style, agt)
note = ''
if agroup.note:
for agn in agroup.note:
note += '<p class="note" style="{0}">{1}</p>'.format(note_style, agn)
try:
dt_bgcolor = COLOR_MAP[agroup.highlightcolor]['bg']
dt_fgcolor = COLOR_MAP[agroup.highlightcolor]['fg']
except:
if agroup.highlightcolor is None:
msg = "No highlight color specified, using Default"
else:
msg = "Unknown color '%s' specified" % agroup.highlightcolor
self._log_location(msg)
dt_bgcolor = COLOR_MAP['Default']['bg']
dt_fgcolor = COLOR_MAP['Default']['fg']
if agroup.hash is not None:
# Use existing hash when re-rendering
hash = agroup.hash
else:
m = hashlib.md5()
m.update(text)
m.update(note)
hash = m.hexdigest()
divTag = Tag(BeautifulSoup(), 'div')
content_args = {
'color': agroup.highlightcolor,
'friendly_timestamp': friendly_timestamp,
'location': location,
'note': note,
'text': text,
'ts_style': datetime_style.format(dt_bgcolor, dt_fgcolor),
'unix_timestamp': agroup.timestamp,
}
divTag.insert(0, comments_body.format(**content_args))
divTag['class'] = "annotation"
divTag['genre'] = ''
if agroup.genre:
divTag['genre'] = escape(agroup.genre)
divTag['hash'] = hash
divTag['location_sort'] = agroup.location_sort
divTag['reader'] = agroup.reader_app
divTag['style'] = ANNOTATION_DIV_STYLE
soup.div.insert(dtc, divTag)
dtc += 1
if i < len(self.annotations) - 1 and \
plugin_prefs.get('appearance_hr_checkbox', False):
soup.div.insert(dtc, plugin_prefs.get('HORIZONTAL_RULE', '<hr width="80%" />'))
dtc += 1
#return unicode(soup.renderContents())
return soup
class BookNotes(object, Logger):
'''
A simple class to render and re-render Book notes
'''
def construct(self, book_notes):
'''
Given a list of notes, render HTML
'''
soup = None
if book_notes:
soup = BeautifulSoup('''<div class="{0}"></div>'''.format('book_notes'))
for note in book_notes:
div_tag = Tag(soup, 'div', [('class', "book_note")])
p_tag = Tag(soup, 'p', [('class', "book_note"),
('style', "{0}".format(self._get_note_style()))])
p_tag.append(note)
div_tag.append(p_tag)
soup.div.append(div_tag)
return soup
def reconstruct(self, soup):
'''
Update style attribute
'''
p_tags = soup.findAll('p', 'book_note')
for p_tag in p_tags:
p_tag['style'] = self._get_note_style()
return soup
def _get_note_style(self):
'''
Get the current CSS for book_notes
'''
from calibre_plugins.marvin_manager.appearance import default_elements
stored_css = plugin_prefs.get('appearance_css', default_elements)
note_style = ''
for element in stored_css:
if element['name'] == 'Note':
note_style = re.sub('\n', '', element['css'])
break
else:
_log_location("ERROR: Unable to find 'Note' in stored_css")
return note_style
class BookmarkNotes(object, Logger):
'''
A simple class to render and re-render Bookmark notes
'''
BOOKMARK_TEMPLATE = (
'<div class="bookmark" location_sort="{0}">'
'<div class="{1}"></div>'
'<table class="bookmark">'
'<tbody><tr><td class="location" style="{2}">{3}'
'</td></tr></tbody></table>'
'<p class="bookmark_note" style="{4}">{5}</p>'
'</div>'
)
def construct(self, bookmark_notes):
'''
bookmark_notes: {loc_sort: {color, location, note}…}
Optionally include <hr> between booknotes
'''
soup = None
if bookmark_notes:
soup = BeautifulSoup('''<div class="{0}"></div>'''.format('bookmark_notes'))
dtc = 0
for i, location_sort in enumerate(sorted(bookmark_notes.keys())):
soup.div.insert(dtc, self.BOOKMARK_TEMPLATE.format(
location_sort,
bookmark_notes[location_sort]['color'],
self._get_style('Location'),
bookmark_notes[location_sort]['location'],
self._get_style('Note'),
bookmark_notes[location_sort]['note']))
dtc += 1
if (i < len(bookmark_notes) - 1 and
plugin_prefs.get('appearance_hr_checkbox', False)):
soup.div.insert(dtc, plugin_prefs.get('HORIZONTAL_RULE', '<hr width="80%" />'))
dtc += 1
return soup
def reconstruct(self, soup):
'''
Rebuild bookmark_notes with current note style
'''
bookmark_notes = self._deconstruct(soup)
reconstructed_soup = self.construct(bookmark_notes)
return reconstructed_soup
def _deconstruct(self, soup):
'''
Extract dict of bookmark parameters from extant bookmarks
<p> may have imbedded <br/> elements
'''
bookmark_notes = {}
div_tags = soup.findAll('div', 'bookmark')
for div_tag in div_tags:
location_sort = div_tag['location_sort']
bookmark_notes[location_sort] = {
'color': div_tag.div['class'],
'location': div_tag.find('td', 'location').string,
'note': unicode(div_tag.find('p', 'bookmark_note').renderContents())
}
return bookmark_notes
def _get_style(self, target):
'''
Get the current CSS for target
'''
from calibre_plugins.marvin_manager.appearance import default_elements
stored_css = plugin_prefs.get('appearance_css', default_elements)
style = ''
for element in stored_css:
if element['name'] == target:
style = re.sub('\n', '', element['css'])
break
else:
self._log_location("ERROR: Unable to find '{0}' in stored_css".format(target))
return style
def merge_annotations(parent, cid, old_soup, new_soup):
'''
old_soup, new_soup: BeautifulSoup()
Need to strip <hr>, re-sort based on location, build new merged_soup
with optional interleaved <hr> elements.
'''
TRANSIENT_DB = 'transient'
if False:
'''
Older technique: Use hashes to merge annotations
'''
#Get the hashes of any existing annotations
oiuas = old_soup.findAll('div', 'annotation')
old_hashes = set([ua['hash'] for ua in oiuas])
# Extract old user_annotations
ouas = old_soup.find('div', 'user_annotations')
if ouas:
ouas.extract()
# Capture existing annotations
parent.opts.db.capture_content(ouas, cid, TRANSIENT_DB)
# Regurgitate old_soup with current CSS
regurgitated_soup = BeautifulSoup(parent.opts.db.rerender_to_html(TRANSIENT_DB, cid))
# Find new annotations
uas = new_soup.findAll('div', 'annotation')
new_hashes = set([ua['hash'] for ua in uas])
updates = list(new_hashes.difference(old_hashes))
if len(updates) and ouas is not None:
# Append new to regurgitated
dtc = len(regurgitated_soup.div)
for new_annotation_id in updates:
new_annotation = new_soup.find('div', {'hash': new_annotation_id})
regurgitated_soup.div.insert(dtc, new_annotation)
dtc += 1
if old_soup:
merged_soup = unicode(old_soup) + unicode(sort_merged_annotations(regurgitated_soup))
else:
merged_soup = unicode(sort_merged_annotations(regurgitated_soup))
else:
if old_soup:
merged_soup = unicode(old_soup) + unicode(new_soup)
else:
merged_soup = unicode(new_soup)
return merged_soup
else:
'''
Newer technique: Use timestamps to merge annotations
'''
timestamps = {}
# Get the timestamps and hashes of the stored annotations
suas = old_soup.findAll('div', 'annotation')
for sua in suas:
#print("sua: %s" % sua.prettify())
timestamp = sua.find('td', 'timestamp')['uts']
timestamps[timestamp] = {'stored_hash': sua['hash']}
# Rerender stored annotations
ouas = old_soup.find('div', 'user_annotations')
if ouas:
ouas.extract()
# Capture existing annotations
parent.opts.db.capture_content(ouas, cid, TRANSIENT_DB)
# Regurgitate annotations with current CSS
rerendered_annotations = parent.opts.db.rerender_to_html(TRANSIENT_DB, cid)
regurgitated_soup = BeautifulSoup(rerendered_annotations)
# Add device annotation timestamps and hashes
duas = new_soup.findAll('div', 'annotation')
for dua in duas:
timestamp = dua.find('td', 'timestamp')['uts']
if timestamp in timestamps:
timestamps[timestamp]['device_hash'] = dua['hash']
else:
timestamps[timestamp] = {'device_hash': dua['hash']}
merged_annotations = Tag(BeautifulSoup(), 'div',
[('class', "user_annotations"), ('style','margin:0')])
for ts in sorted(timestamps):
if 'stored_hash' in timestamps[ts] and not 'device_hash' in timestamps[ts]:
# Stored only - add from regurgitated_soup
annotation = regurgitated_soup.find('div', {'hash': timestamps[ts]['stored_hash']})
elif not 'stored_hash' in timestamps[ts] and 'device_hash' in timestamps[ts]:
# Device only - add from new_soup
annotation = new_soup.find('div', {'hash': timestamps[ts]['device_hash']})
elif timestamps[ts]['stored_hash'] == timestamps[ts]['device_hash']:
# Stored matches device - add from regurgitated_soup, as user may have modified
annotation = regurgitated_soup.find('div', {'hash': timestamps[ts]['stored_hash']})
elif timestamps[ts]['stored_hash'] != timestamps[ts]['device_hash']:
# Device has been updated since initial capture - add from new_soup
annotation = new_soup.find('div', {'hash': timestamps[ts]['device_hash']})
else:
continue
merged_annotations.append(annotation)
merged_annotations = sort_merged_annotations(merged_annotations)
# Update new_soup with merged_annotations
new_soup_uas = new_soup.find('div', 'user_annotations')
new_soup_uas.replaceWith(merged_annotations)
return unicode(new_soup)
def merge_annotations_with_comments(parent, cid, comments_soup, new_soup):
'''
comments_soup: comments potentially with user_annotations
'''
# Prepare a new COMMENTS_DIVIDER
comments_divider = '<div class="comments_divider"><p style="text-align:center;margin:1em 0 1em 0">{0}</p></div>'.format(
plugin_prefs.get('COMMENTS_DIVIDER', '· · • · ✦ · • · ·'))
# Remove the old comments_divider
cds = comments_soup.find('div', 'comments_divider')
if cds:
cds.extract()
# Existing annotations?
uas = comments_soup.find('div', 'user_annotations')
if uas:
# Save the existing annotations to old_soup
old_soup = BeautifulSoup(unicode(uas))
# Remove any hrs from old_soup
hrs = old_soup.findAll('hr')
if hrs:
for hr in hrs:
hr.extract()
# Remove the existing annotations from comments_soup
uas.extract()
# Merge old_soup with new_soup
merged_soup = unicode(comments_soup) + \
unicode(comments_divider) + \
unicode(merge_annotations(parent, cid, old_soup, new_soup))
else:
# No existing, just merge comments_soup with already sorted new_soup
merged_soup = unicode(comments_soup) + \
unicode(comments_divider) + \
unicode(new_soup)
return merged_soup
def sort_merged_annotations(merged_soup):
'''
Input: a combined group of user annotations
Output: sorted by location
'''
include_hr = plugin_prefs.get('appearance_hr_checkbox', False)
locations = merged_soup.findAll(location_sort=True)
locs = [loc['location_sort'] for loc in locations]
locs.sort()
sorted_soup = BeautifulSoup(ANNOTATIONS_HEADER)
dtc = 0
for i, loc in enumerate(locs):
next_div = merged_soup.find(attrs={'location_sort': loc})
sorted_soup.div.insert(dtc, next_div)
dtc += 1
if include_hr and i < len(locs) - 1:
sorted_soup.div.insert(dtc, plugin_prefs.get('HORIZONTAL_RULE', '<hr width="80%" />'))
dtc += 1
return sorted_soup