Debian Codegraph @

src/pyj/book_list/local_books.pyj

raw
1 # vim:fileencoding=utf-8
2 # License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
3 from __python__ import bound_methods, hash_literals
4
5 from elementmaker import E
6 from gettext import gettext as _, ngettext
7
8 from book_list.globals import get_db
9 from book_list.library_data import library_data
10 from book_list.router import home, open_book
11 from book_list.top_bar import add_button, create_top_bar
12 from book_list.ui import set_panel_handler
13 from book_list.views import DEFAULT_MODE, get_view_mode, setup_view_mode, populate_book_list_toolbar
14 from dom import clear, ensure_id
15 from modals import create_custom_dialog, error_dialog
16 from utils import conditional_timeout, safe_set_inner_html
17 from widgets import create_button, enable_escape_key, create_pager_widget, create_search_widget
18
19 # Same as book_list.views CLASS_NAME (library list root), for shared CSS
20 BOOK_LIST_CONTAINER_CLASS = 'book-list-container'
21 CLASS_NAME = 'local-books-list'
22
23 book_list_data = {}
24 LOCAL_SEARCH_METADATA_FIELDS = [
25 'title', 'authors', 'author_sort', 'publisher', 'series', 'tags',
26 'formats', 'identifiers', 'languages', 'lang_names'
27 ]
28
29
30 def component(name):
31 return document.getElementById(book_list_data.container_id).querySelector(f'[data-component="{name}"]')
32
33
34 def add_search_text(parts, value):
35 if value is None or value is undefined:
36 return
37 if Array.isArray(value):
38 for x in value:
39 add_search_text(parts, x)
40 elif jstype(value) is 'object':
41 for key in Object.keys(value):
42 add_search_text(parts, value[key])
43 else:
44 parts.push(str(value))
45
46
47 def add_search_mapping_text(parts, value, include_keys=False):
48 if value is None or value is undefined:
49 return
50 if jstype(value) is 'object' and not Array.isArray(value):
51 for key in Object.keys(value):
52 if include_keys:
53 parts.push(key)
54 add_search_text(parts, value[key])
55 else:
56 add_search_text(parts, value)
57
58
59 def metadata_search_text(metadata):
60 parts = []
61 if metadata:
62 for key in LOCAL_SEARCH_METADATA_FIELDS:
63 if key is 'identifiers':
64 add_search_mapping_text(parts, metadata[key], include_keys=True)
65 elif key is 'lang_names':
66 add_search_mapping_text(parts, metadata[key])
67 else:
68 add_search_text(parts, metadata[key])
69 return parts.join('\n').toLowerCase()
70
71
72 def normalize_local_search_query(query):
73 return (query or '').toLowerCase().replace(/\s+/g, ' ').trim()
74
75
76 def matching_book_indices_for_query(book_data, book_indices, query):
77 tokens = [x for x in normalize_local_search_query(query).split(' ') if x]
78 if not tokens.length:
79 return list(book_indices)
80 ans = []
81 for book_idx in book_indices:
82 book = book_data[book_idx]
83 text = book._local_books_search_text
84 if text is undefined:
85 text = book._local_books_search_text = metadata_search_text(book.metadata)
86 matched = True
87 for token in tokens:
88 if text.indexOf(token) < 0:
89 matched = False
90 break
91 if matched:
92 ans.append(book_idx)
93 return ans
94
95
96 def clear_grid():
97 # Book list lives inside .cs-book-list-wrap (same as library view); replace in-place.
98 e = component('book_list')
99 if not e or not e.parentNode:
100 return
101 parent = e.parentNode
102 bl = E.div(data_component='book_list')
103 parent.insertBefore(bl, e)
104 parent.removeChild(e)
105 book_list_data.init_grid(bl)
106
107
108 def read_book(book, book_idx):
109 library_id, book_id, fmt = book.key
110 open_book(book_id, fmt, library_id)
111
112
113 def delete_book(book, book_idx):
114 db = get_db()
115 db.delete_book(book, def (book, err_string):
116 if err_string:
117 error_dialog(_('Failed to delete book'), err_string)
118 return
119 books = [book_list_data.book_data[i] for i in book_list_data.all_books if i is not book_idx]
120 show_recent_stage2.call(book_list_data.container_id, books, book_list_data.search_query)
121 )
122
123
124 def confirm_delete_all():
125 num_of_books = book_list_data.all_books?.length
126 if not num_of_books:
127 return
128 create_custom_dialog(_('Are you sure?'), def (parent, close_modal):
129 def action(doit):
130 if doit:
131 clear(parent)
132 delete_all(parent, close_modal)
133 else:
134 close_modal()
135 msg = ngettext(
136 'This will remove the downloaded book from local storage. Are you sure?',
137 'This will remove all {} downloaded books from local storage. Are you sure?',
138 num_of_books).format(num_of_books)
139 m = E.div()
140 safe_set_inner_html(m, msg)
141 parent.appendChild(E.div(
142 m,
143 E.div(class_='button-box',
144 create_button(_('Cancel'), None, action.bind(None, False)),
145 create_button(_('OK'), None, action.bind(None, True), highlight=True),
146 )
147 ))
148 )
149
150
151 def delete_all(msg_parent, close_modal):
152 db = get_db()
153 books = list(book_list_data.all_books)
154
155 def refresh():
156 show_recent_stage2.call(book_list_data.container_id, [book_list_data.book_data[i] for i in books], book_list_data.search_query)
157
158 def delete_one():
159 if not books.length:
160 close_modal()
161 refresh()
162 return
163 clear(msg_parent)
164 safe_set_inner_html(msg_parent, ngettext(
165 'Deleting one book, please wait...',
166 'Deleting {} books, please wait...',
167 books.length or 0).format(books.length)
168 )
169 book_to_delete = books.pop()
170 db.delete_book(book_list_data.book_data[book_to_delete], def (book, err_string):
171 if err_string:
172 close_modal()
173 refresh()
174 error_dialog(_('Failed to delete book'), err_string)
175 else:
176 delete_one()
177 )
178 delete_one()
179
180
181 def on_select(book, book_idx):
182 title = this
183
184 create_custom_dialog(title, def (parent, close_modal):
185 def action(which):
186 close_modal()
187 which(book, book_idx)
188 parent.appendChild(E.div(
189 E.div(_('What would you like to do with this book?')),
190 E.div(class_='button-box',
191 create_button(_('Read'), 'book', action.bind(None, read_book)),
192 create_button(_('Delete'), 'trash', action.bind(None, delete_book)),
193 )
194 ))
195 )
196
197
198 def show_cover(blob, name, mt, book):
199 img = document.getElementById(this)
200 if img:
201 img.src = window.URL.createObjectURL(blob)
202
203
204 def create_image(book_idx, max_width, max_height, on_load):
205 img = new Image()
206 img.onerror = def ():
207 if this.src:
208 window.URL.revokeObjectURL(this.src)
209 on_load(this, 'error')
210 img.onload = def ():
211 if this.src:
212 window.URL.revokeObjectURL(this.src)
213 on_load(this, 'load')
214 book = book_list_data.book_data[book_idx]
215 if book?.metadata:
216 authors = book.metadata.authors.join(' & ') if book.metadata.authors else _('Unknown')
217 img.setAttribute('alt', _('{} by {}').format(
218 book.metadata.title, authors))
219 if book?.cover_name:
220 img_id = ensure_id(img, 'local-cover-')
221 get_db().get_file(book, book.cover_name, show_cover.bind(img_id))
222 return img
223
224
225 def render_book(book_idx):
226 book = book_list_data.book_data[book_idx]
227 return book_list_data.render_book(book_idx, book.metadata, create_image, on_select.bind(book.metadata.title, book, book_idx))
228
229
230 def render_books(books):
231 div = component('book_list')
232 if books is None or books is undefined:
233 books = book_list_data.books
234 for book_idx in books:
235 child = render_book(book_idx)
236 if child is not None:
237 book_list_data.append_item(div, child)
238
239
240 def update_empty_message():
241 msg = component('empty_message')
242 if not msg:
243 return
244 if book_list_data.books.length:
245 msg.style.display = 'none'
246 return
247 msg.style.display = 'block'
248 msg.textContent = (
249 _('No downloaded books match your search') if normalize_local_search_query(book_list_data.search_query) else
250 _('No downloaded books present')
251 )
252
253
254 def apply_search(query):
255 book_list_data.search_query = query or ''
256 book_list_data.books = matching_book_indices_for_query(book_list_data.book_data, book_list_data.all_books, query)
257 clear_grid()
258 render_books()
259 update_empty_message()
260
261
262 def apply_view_mode(mode):
263 mode = mode or DEFAULT_MODE
264 # custom_list requires field_metadata from the server; fall back to the
265 # default grid when offline so downloaded books are still visible.
266 if mode is 'custom_list' and not library_data.field_metadata:
267 mode = DEFAULT_MODE
268 if book_list_data.mode is mode:
269 return mode
270 setup_view_mode(mode, book_list_data)
271 clear_grid()
272 render_books()
273 update_empty_message()
274 return mode
275
276
277 def create_search_box():
278 return create_search_widget(
279 apply_search, value=book_list_data.search_query, placeholder=_('Search downloaded books'), live_searching=True)
280
281
282 def create_books_list(container, books, search_query=None):
283 clear(container)
284 book_list_data.container_id = ensure_id(container)
285 book_list_data.book_data = {i: book for i, book in enumerate(books)}
286 book_list_data.all_books = list(range(books.length))
287 book_list_data.search_query = search_query or ''
288 book_list_data.books = matching_book_indices_for_query(book_list_data.book_data, book_list_data.all_books, search_query)
289 book_list_data.mode = None
290 book_list_data.thumbnail_cache = {}
291 container.classList.add(BOOK_LIST_CONTAINER_CLASS)
292 if not books.length:
293 container.appendChild(E.div(
294 data_component='empty_message',
295 style='margin: 1rem 0',
296 _('No downloaded books present')
297 ))
298 return
299
300 pw = create_pager_widget()
301 pw.top_row.appendChild(create_search_box())
302 pw.set_top_row_visibility(True)
303 mode = get_view_mode()
304 if mode is 'custom_list' and not library_data.field_metadata:
305 mode = DEFAULT_MODE
306 populate_book_list_toolbar(pw.middle_row, False, apply_view_mode, mode)
307 pw.set_middle_row_visibility(True)
308 pw.set_enabled(False, False)
309
310 container.appendChild(pw.container)
311 container.appendChild(E.div(data_component='empty_message', style='display: none; margin: 1rem 0'))
312 container.appendChild(E.div(data_component='book_list'))
313 apply_view_mode(mode)
314
315
316 def show_recent_stage2(books, search_query=None):
317 container = document.getElementById(this)
318 if not container:
319 return
320 create_books_list(container, books, search_query)
321
322
323 def show_recent():
324 container = this
325 db = get_db()
326 # Because we want this to work in offline mode via service worker, we cant
327 # wait for library_data.field_metadata instead use a display mode that does
328 # not require it.
329 if not db.initialized:
330 conditional_timeout(container.id, 5, show_recent)
331 return
332 if db.is_ok:
333 db.get_downloaded_books(show_recent_stage2.bind(container.id))
334 else:
335 error_dialog(_('Database not initialized'),
336 db.initialize_error_msg)
337
338
339 def init(container_id):
340 container = document.getElementById(container_id)
341 on_close = home
342 create_top_bar(container, title=_('Downloaded books'), action=on_close, icon='home')
343 add_button(container, 'trash', confirm_delete_all, _('Delete all downloaded books'))
344 # book list
345 recent = E.div(class_=CLASS_NAME + ' ' + BOOK_LIST_CONTAINER_CLASS)
346 recent_container_id = ensure_id(recent)
347 container.appendChild(recent)
348 recent.appendChild(E.div(
349 style='margin: 1rem 0',
350 _('Loading downloaded books from local storage, please wait...')
351 ))
352 conditional_timeout(recent_container_id, 5, show_recent)
353 enable_escape_key(container, on_close)
354
355
356 def set_panel_handlers():
357 set_panel_handler('local_books', init)