def set_main_cover(): tome_id = request.args[0] file_hash = request.args[1] file_extension = request.args[2] tome = pdb.get_tome(tome_id) form = _set_main_cover_form() title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u'Set Cover for {} - Montag'.format(title_text) file_size = pyrosetup.fileserver().get_local_file_size(file_hash) if form.process(keepvalues=True).accepted: fidelity = read_form_field(form, 'fidelity') pdb.link_tome_to_file(tome_id, file_hash, file_size, file_extension, FileType.Cover, fidelity) doc = pdb.get_tome_document_by_guid(tome['guid'], hide_private_tags=False) other_files = filter(lambda x: x['hash'] != file_hash, doc['files']) tome_file_doc = filter(lambda x: x['hash'] == file_hash, doc['files'])[0] tome_file_doc['fidelity'] = fidelity other_files.append(tome_file_doc) doc['files'] = other_files pdb.load_own_tome_document(doc) redirect(URL('default', 'view_tome', args=(tome['guid']))) return {'tome': tome, 'file_hash': file_hash, 'file_extension': file_extension, 'form': form}
def edit_tome_file_link(): tome_id = request.args[0] file_hash = request.args[1] tome = pdb.get_tome(tome_id) files = pdb.get_tome_files(tome_id, file_type=pydb.FileType.Content, include_local_file_info=True) tome_files = filter(lambda x: x['hash'] == file_hash, files) tome_file = tome_files[0] form = SQLFORM.factory(Field('file_extension', default=db_str_to_form(tome_file['file_extension'])), Field('fidelity', requires=FidelityValidator(), default=tome_file['fidelity']+0.1), submit_button='Save') title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u"Edit Files {} - Montag".format(title_text) field_names = ['file_extension', 'fidelity'] if form.process(keepvalues=True).accepted: doc = pdb.get_tome_document_by_guid(tome['guid'], hide_private_tags=False) other_files = filter(lambda x: x['hash'] != file_hash, doc['files']) tome_file_doc = filter(lambda x: x['hash'] == file_hash, doc['files'])[0] for f in field_names: tome_file_doc[f] = read_form_field(form, f) other_files.append(tome_file_doc) doc['files'] = other_files pdb.load_own_tome_document(doc) response.flash = 'Stored new values' redirect(URL('edit_tome', args=(tome['guid']), anchor='files')) elif form.errors: response.flash = 'form has errors' return dict(form=form, tome=tome, file=tome_file)
def edit_covers(): tome_id = request.args[0] tome = pdb.get_tome(tome_id) tome_guid = tome['guid'] tome = pdb.get_tome_document_by_guid(tome_guid, include_local_file_info=True, include_author_detail=True, keep_id=True, hide_private_tags=False) title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u'Edit Cover for {} - Montag'.format(title_text) available_covers = [] available_content = [] relevant_files = network_params.relevant_items(tome['files']) relevant_local_files = filter(lambda f: f['has_local_copy'], relevant_files) for tome_file in relevant_local_files: if tome_file['file_type'] == pydb.FileType.Content: if tome_file['file_extension'] != 'txt': available_content.append(tome_file) elif tome_file['file_type'] == pydb.FileType.Cover: available_covers.append(tome_file) else: raise ValueError('Invalid value for file type') locally_available_covers = filter(lambda x: x['has_local_copy'], available_covers) if locally_available_covers: current_cover = max(locally_available_covers, key=lambda x: x['fidelity']) else: current_cover = None return {'tome': tome, 'available_covers': available_covers, 'available_content': available_content, 'current_cover': current_cover}
def link_tome_to_file(): tome_id = request.args[0] tome = pdb.get_tome(tome_id) form = SQLFORM.factory(Field('hash'), Field('file_extension', default="epub"), Field('fidelity', requires=FidelityValidator(), default=70), submit_button='Save') title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u'Edit Files of {} - Montag'.format(title_text) if form.process(keepvalues=True).accepted: file_hash = read_form_field(form, 'hash') file_extension = read_form_field(form, 'file_extension') fidelity = read_form_field(form, 'fidelity') local_file_size = pyrosetup.fileserver().get_local_file_size(file_hash) if not local_file_size: response.flash = 'This file is not known to the database, please check the hash' else: pdb.link_tome_to_file(tome_id, file_hash, local_file_size, file_extension, FileType.Content, fidelity) session.flash = 'Added new file link' redirect(URL('edit_tome_file_link', args=(tome_id, file_hash))) elif form.errors: response.flash = 'form has errors' return dict(form=form, tome=tome)
def add_metadata(source_stream, output_stream, author_docs, tome_doc, tome_file): author_names = {author_doc['name'] for author_doc in author_docs} tome_title = coalesce_title(tome_doc['title'], tome_doc['subtitle']) short_file_hash = tome_file['hash'][:4] file_title = u"{} - {} ({})".format(', '.join(author_names), tome_title, short_file_hash) clear_metadata(source_stream, output_stream, new_title=file_title) return True
def view_tome(): tome_guid = request.args[0] tome = pdb.get_tome_document_by_guid(tome_guid, keep_id=True, include_local_file_info=True, include_author_detail=True, hide_private_tags=False) if 'title' not in tome: tome_guid = pdb.get_tome_fusion_target_guid(tome_guid) if tome_guid: redirect(URL('view_tome', args=tome_guid)) title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u"{} - Montag".format(title_text) return { 'tome': tome }
def upload_cover(): tome_id = request.args[0] tome = pdb.get_tome(tome_id) if tome is None: response.flash = 'Tome not found' return dict(form=None, tome=None) title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u"Upload Cover for {} - Montag".format(title_text) response.enable_dropzone = True form = _upload_cover_form() if form.process(keepvalues=True, dbio=False).accepted: f = request.vars.file is_dropzone = False if isinstance(f, list): # dropzone uploads result in lists f = f[1] is_dropzone = True (_, extension_with_dot) = os.path.splitext(f.filename) file_extension = extension_with_dot[1:] (file_id, file_hash, file_size) = _insert_file(f.file, f.filename) pdb.link_tome_to_file(tome_id, file_hash, file_size, file_extension, FileType.Cover, fidelity=DEFAULT_ADD_FIDELITY) response.flash = 'Successfully uploaded cover' target_url = URL(f='view_tome', c='default', args=(tome['guid'])) if is_dropzone: return target_url else: redirect(target_url) elif form.errors: response.flash = 'form has errors' return dict(form=form, tome=tome)
def edit_tome_author_link(): tome_id = request.args[0] author_id = request.args[1] tome = pdb.get_tome(tome_id) tome_authors = pdb.get_tome_authors(tome_id) for ta in tome_authors: if int(ta['id']) == int(author_id): tome_author = ta break else: return dict(error="Tome and author not linked?", form=None, tome=tome, author=None, authors=tome_authors) author_guid = tome_author['guid'] form = SQLFORM.factory(Field('order', default=tome_author['author_order']), Field('fidelity', requires=FidelityValidator(), default=tome_author['link_fidelity']+0.1), submit_button='Save') title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u"Edit Author Link {} <=> {} - Montag".format(tome_author['name'], title_text) if form.process(keepvalues=True).accepted: doc = pdb.get_tome_document_by_guid(tome['guid'], hide_private_tags=False) other_authors = filter(lambda x: x['guid'] != author_guid, doc['authors']) tome_author_doc = filter(lambda x: x['guid'] == author_guid, doc['authors'])[0] for f in ('order', 'fidelity'): tome_author_doc[f] = read_form_field(form, f) other_authors.append(tome_author_doc) doc['authors'] = other_authors pdb.load_own_tome_document(doc) tome_authors = pdb.get_tome_authors(tome_id) response.flash = 'Stored new values' redirect(URL('edit_tome', args=(tome['guid']), anchor='authors')) elif form.errors: response.flash = 'form has errors' return dict(form=form, tome=tome, author=tome_author, authors=tome_authors)
def upload_file_to_tome(): tome_guid = request.args[0] response.enable_dropzone = True form = _create_upload_form() tome = pdb.get_tome_by_guid(tome_guid) if tome is None: response.title = u"Upload File - Montag" response.flash = 'Tome not found' return dict(form=form, tome=None) title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u"Upload File to {} - Montag".format(title_text) if form.accepts(request.vars): f = request.vars.file is_dropzone = False if isinstance(f, list): # dropzone uploads result in lists f = f[1] is_dropzone = True _, extension_with_dot = os.path.splitext(f.filename) extension = extension_with_dot[1:] fidelity = DEFAULT_ADD_FIDELITY (_, file_hash, size) = _insert_file(f.file, f.filename) pdb.link_tome_to_file(tome['id'], file_hash, size, extension, FileType.Content, fidelity) target_url = URL('default', 'view_tome', args=tome_guid) if is_dropzone: return target_url else: redirect(target_url) elif form.errors: response.flash = 'form has errors' return dict(form=form, tome=tome)
def set_cover_from_content(): tome_id = request.args[0] content_hash = request.args[1] content_extension = request.args[2] only_display_cover_afterwards = request.args[3] if only_display_cover_afterwards.lower() == 'false': only_display_cover_afterwards = False tome = pdb.get_tome(tome_id) form = _set_cover_from_content_form() title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u'Set Cover for {} - Montag'.format(title_text) if form.process(keepvalues=True).accepted: fidelity = read_form_field(form, 'fidelity') cover_contents = _extract_image_from_content(content_hash, content_extension) if cover_contents is None: session.flash('Cover could not be loaded - sorry!') redirect(URL('default', 'view_tome', args=(tome['guid']))) return file_extension = 'jpg' fd_cover, path_cover = tempfile.mkstemp('.' + file_extension) with os.fdopen(fd_cover, 'wb') as cover_file: cover_file.write(cover_contents.getvalue()) file_server = pyrosetup.fileserver() (local_file_id, file_hash, file_size) = file_server.add_file_from_local_disk(path_cover, file_extension, move_file=True) pdb.link_tome_to_file(tome_id, file_hash, file_size, file_extension, FileType.Cover, fidelity) if only_display_cover_afterwards: redirect(URL('covers', 'get_cover_image', args=(file_hash, file_extension))) else: redirect(URL('default', 'view_tome', args=(tome['guid']))) return {'tome': tome, 'content_hash': content_hash, 'content_extension': content_extension, 'form': form}
def add_metadata(instream, outstream, author_docs, tome_doc, tome_file): try: with zipfile.ZipFile(instream) as inzip: opf_path = _get_path_of_content_opf(inzip) opf_content = _read_content_opf(inzip, opf_path) root = defused_etree.fromstring(opf_content) for main_element in root: logger.debug("main el %s" % main_element.tag) if re.match(".*metadata$", main_element.tag): logger.debug("Found metadata tag, cleaning") while list(main_element): # do not remove using a for loop - this will skip elements in python 2.7.5! node_to_remove = list(main_element)[0] logger.debug("Removing node %s" % node_to_remove.tag) main_element.remove(node_to_remove) for author_doc in author_docs: author_el = ElementTree.SubElement(main_element, "{http://purl.org/dc/elements/1.1/}creator", {"{http://www.idpf.org/2007/opf}role": "aut"}) author_el.text = author_doc['name'] title_el = ElementTree.SubElement(main_element, "{http://purl.org/dc/elements/1.1/}title") title_el.text = title.coalesce_title(tome_doc['title'], tome_doc['subtitle']) language_el = ElementTree.SubElement(main_element, "{http://purl.org/dc/elements/1.1/}language") language_el.text = tome_doc['principal_language'] with zipfile.ZipFile(outstream, 'w') as outzip: _copy_zip_contents(inzip, outzip, [opf_path]) new_content = ElementTree.tostring(root) _write_content_opf(outzip, opf_path, new_content) except zipfile.BadZipfile: raise ValueError("Unable to open epub zip") instream.seek(0) return True
def link_tome_to_author(): tome_id = request.args[0] tome = pdb.get_tome(tome_id) tome_authors = pdb.get_tome_authors(tome_id) if tome_authors: last_tome_author = max(tome_authors, key=lambda x: float(x['author_order'])) max_author_order = last_tome_author['author_order'] else: max_author_order = 0 form = SQLFORM.factory(Field('author_name'), Field('order', default=max_author_order+1, label='Order Value'), Field('fidelity', requires=FidelityValidator(), default=70), submit_button='Save') title_text = title.coalesce_title(tome['title'], tome['subtitle']) response.title = u"Add Author to {} - Montag".format(title_text) if form.process(keepvalues=True).accepted: author_name = read_form_field(form, 'author_name') fidelity = read_form_field(form, 'fidelity') author_order = float(read_form_field(form, 'order')) author_ids = pdb.find_or_create_authors([author_name], fidelity) author_id = author_ids[0] pdb.link_tome_to_author(tome_id, author_id, author_order, fidelity) session.flash = 'Added author to tome' redirect(URL('edit_tome', args=(tome['guid']), anchor='authors')) elif form.errors: response.flash = 'form has errors' return dict(form=form, tome=tome, authors=tome_authors)
def tome_link(tome_info): title_text = title.coalesce_title(tome_info['title'], tome_info['subtitle']) result = A(title_text, _class="tome_link", _href=URL('default', 'view_tome', args=[tome_info['guid']])) return result
def _edit_tome(tome_doc): if not tome_doc: return "Tome no longer existing!" title_text = title.coalesce_title(tome_doc['title'], tome_doc['subtitle']) response.title = u"Edit {} - Montag".format(title_text) field_names = ['title', 'subtitle', 'edition', 'principal_language', 'publication_year', 'tags', 'type', 'fidelity'] syn_field_names = ['content', 'fidelity'] tome_id = tome_doc['id'] required_tome_fidelity = pdb.calculate_required_tome_fidelity(tome_id) form = _tome_edit_form(tome_doc, required_tome_fidelity) synforms = list() relevant_synopses = list(network_params.relevant_items(tome_doc['synopses'])) tome_doc['synopses'] = relevant_synopses for synopsis in relevant_synopses: synforms.append(_tome_synopses_form(synopsis)) if 'guid' in request.vars: synopsis_guid = request.vars.guid formname = u'edit_synopsis_{}'.format(synopsis_guid) for syn_idx, synform in enumerate(synforms): if synform.process(session=None, formname=formname, keepvalues=True).accepted: if not synopsis_guid: raise ValueError("No synopsis guid found") for synopsis in tome_doc['synopses']: if synopsis['guid'] == synopsis_guid: synopsis_to_edit = synopsis break else: synopsis_to_edit = {'guid': synopsis_guid} tome_doc['synopses'].append(synopsis_to_edit) for sf in syn_field_names: synopsis_to_edit[sf] = read_form_field(synform, sf) pdb.load_own_tome_document(tome_doc) redirect(URL('edit_tome', args=(tome_doc['guid']), anchor='synopses')) elif synform.errors: response.flash = 'form has errors' if form.process(session=None, formname='edit_tome', keepvalues=True).accepted: for f in field_names: tome_doc[f] = read_form_field(form, f) if 'authors' not in tome_doc: tome_doc['authors'] = [] if 'files' not in tome_doc: tome_doc['files'] = [] if 'publication_year' not in tome_doc: tome_doc['publication_year'] = None elif tome_doc['publication_year'] == 'None': tome_doc['publication_year'] = None pdb.load_own_tome_document(tome_doc) redirect(URL('view_tome', args=(tome_doc['guid']))) elif form.errors: response.flash = 'form has errors' tome_doc['id'] = tome_id return dict(form=form, tome=tome_doc, tome_id=tome_id, synforms=synforms, required_fidelity=required_tome_fidelity)