Python flask_babel.gettext() Examples

The following are 30 code examples of flask_babel.gettext(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask_babel , or try the search function .
Example #1
Source File: db.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def run(self):
        while True:
            i = self.queue.get()
            if i == 'dummy':
                self.queue.task_done()
                break
            if i['task'] == 'add_format':
                cur_book = self.session.query(Books).filter(Books.id == i['id']).first()
                cur_book.data.append(i['format'])
                try:
                    # db.session.merge(cur_book)
                    self.session.commit()
                except OperationalError as e:
                    self.session.rollback()
                    self.log.error("Database error: %s", e)
                    # self._handleError(_(u"Database error: %(error)s.", error=e))
                    # return
            self.queue.task_done() 
Example #2
Source File: sign.py    From gitlab-tools with GNU General Public License v3.0 6 votes vote down vote up
def validate(self) -> bool:
        rv = Form.validate(self)
        if not rv:
            return False
        user = db.session.query(User).filter(User.username == self.username.data).first()
        # email and password found and match
        if user is None:
            self.username.errors.append(gettext('Username was not found.'))
            return False

        if user.check_password(self.password.data) is False:
            self.password.errors.append(gettext('Wrong password.'))
            return False

        self.user = user
        return True 
Example #3
Source File: helper.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id):
    """Send email with attachments"""
    book = calibre_db.get_book(book_id)

    if convert == 1:
        # returns None if success, otherwise errormessage
        return convert_book_format(book_id, calibrepath, u'epub', book_format.lower(), user_id, kindle_mail)
    if convert == 2:
        # returns None if success, otherwise errormessage
        return convert_book_format(book_id, calibrepath, u'azw3', book_format.lower(), user_id, kindle_mail)

    for entry in iter(book.data):
        if entry.format.upper() == book_format.upper():
            converted_file_name = entry.name + '.' + book_format.lower()
            worker.add_email(_(u"Send to Kindle"), book.path, converted_file_name,
                             config.get_mail_settings(), kindle_mail, user_id,
                             _(u"E-mail: %(book)s", book=book.title), _(u'This e-mail has been sent via Calibre-Web.'))
            return
    return _(u"The requested file could not be read. Maybe wrong permissions?") 
Example #4
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def series_list():
    if current_user.check_visibility(constants.SIDEBAR_SERIES):
        if current_user.series_view == 'list':
            entries = calibre_db.session.query(db.Series, func.count('books_series_link.book').label('count')) \
                .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
                .group_by(text('books_series_link.series')).order_by(db.Series.sort).all()
            charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \
                .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
                .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()
            return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
                                         title=_(u"Series"), page="serieslist", data="series")
        else:
            entries = calibre_db.session.query(db.Books, func.count('books_series_link').label('count')) \
                .join(db.books_series_link).join(db.Series).filter(calibre_db.common_filters()) \
                .group_by(text('books_series_link.series')).order_by(db.Series.sort).all()
            charlist = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('char')) \
                .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters()) \
                .group_by(func.upper(func.substr(db.Series.sort, 1, 1))).all()

            return render_title_template('grid.html', entries=entries, folder='web.books_list', charlist=charlist,
                                         title=_(u"Series"), page="serieslist", data="series", bodyClass="grid-view")
    else:
        abort(404) 
Example #5
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def language_overview():
    if current_user.check_visibility(constants.SIDEBAR_LANGUAGE):
        charlist = list()
        if current_user.filter_language() == u"all":
            languages = calibre_db.speaking_language()
            # ToDo: generate first character list for languages
        else:
            try:
                cur_l = LC.parse(current_user.filter_language())
            except UnknownLocaleError:
                cur_l = None
            languages = calibre_db.session.query(db.Languages).filter(
                db.Languages.lang_code == current_user.filter_language()).all()
            if cur_l:
                languages[0].name = cur_l.get_language_name(get_locale())
            else:
                languages[0].name = _(isoLanguages.get(part3=languages[0].lang_code).name)
        lang_counter = calibre_db.session.query(db.books_languages_link,
                                        func.count('books_languages_link.book').label('bookcount')).group_by(
            text('books_languages_link.lang_code')).all()
        return render_title_template('languages.html', languages=languages, lang_counter=lang_counter,
                                     charlist=charlist, title=_(u"Languages"), page="langlist",
                                     data="language")
    else:
        abort(404) 
Example #6
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def search():
    term = request.args.get("query")
    if term:
        entries = calibre_db.get_search_results(term)
        ids = list()
        for element in entries:
            ids.append(element.id)
        searched_ids[current_user.id] = ids
        return render_title_template('search.html',
                                     searchterm=term,
                                     adv_searchterm=term,
                                     entries=entries,
                                     title=_(u"Search"),
                                     page="search")
    else:
        return render_title_template('search.html',
                                     searchterm="",
                                     title=_(u"Search"),
                                     page="search") 
Example #7
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def render_archived_books(page, order):
    order = order or []
    archived_books = (
        ub.session.query(ub.ArchivedBook)
        .filter(ub.ArchivedBook.user_id == int(current_user.id))
        .filter(ub.ArchivedBook.is_archived == True)
        .all()
    )
    archived_book_ids = [archived_book.book_id for archived_book in archived_books]

    archived_filter = db.Books.id.in_(archived_book_ids)

    entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page,
                                                                                db.Books,
                                                                                archived_filter,
                                                                                order,
                                                                                allow_show_archived=True)

    name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')'
    pagename = "archived"
    return render_title_template('index.html', random=random, entries=entries, pagination=pagination,
                                 title=name, page=pagename)

# ################################### Download/Send ################################################################## 
Example #8
Source File: web.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def send_to_kindle(book_id, book_format, convert):
    if not config.get_mail_server_configured():
        flash(_(u"Please configure the SMTP mail settings first..."), category="error")
    elif current_user.kindle_mail:
        result = send_mail(book_id, book_format, convert, current_user.kindle_mail, config.config_calibre_dir,
                           current_user.nickname)
        if result is None:
            flash(_(u"Book successfully queued for sending to %(kindlemail)s", kindlemail=current_user.kindle_mail),
                  category="success")
            ub.update_download(book_id, int(current_user.id))
        else:
            flash(_(u"Oops! There was an error sending this book: %(res)s", res=result), category="error")
    else:
        flash(_(u"Please update your profile with a valid Send to Kindle E-mail Address."), category="error")
    if "HTTP_REFERER" in request.environ:
        return redirect(request.environ["HTTP_REFERER"])
    else:
        return redirect(url_for('web.index'))


# ################################### Login Logout ################################################################## 
Example #9
Source File: gdrive.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def watch_gdrive():
    if not config.config_google_drive_watch_changes_response:
        with open(gdriveutils.CLIENT_SECRETS, 'r') as settings:
            filedata = json.load(settings)
        if filedata['web']['redirect_uris'][0].endswith('/'):
            filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-((len('/gdrive/callback')+1))]
        else:
            filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-(len('/gdrive/callback'))]
        address = '%s/gdrive/watch/callback' % filedata['web']['redirect_uris'][0]
        notification_id = str(uuid4())
        try:
            result = gdriveutils.watchChange(gdriveutils.Gdrive.Instance().drive, notification_id,
                               'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000)
            config.config_google_drive_watch_changes_response = json.dumps(result)
            # after save(), config_google_drive_watch_changes_response will be a json object, not string
            config.save()
        except HttpError as e:
            reason=json.loads(e.content)['error']['errors'][0]
            if reason['reason'] == u'push.webhookUrlUnauthorized':
                flash(_(u'Callback domain is not verified, please follow steps to verify domain in google developer console'), category="error")
            else:
                flash(reason['message'], category="error")

    return redirect(url_for('admin.configuration')) 
Example #10
Source File: db.py    From calibre-web with GNU General Public License v3.0 6 votes vote down vote up
def speaking_language(self, languages=None):
        from . import get_locale

        if not languages:
            languages = self.session.query(Languages) \
                .join(books_languages_link) \
                .join(Books) \
                .filter(self.common_filters()) \
                .group_by(text('books_languages_link.lang_code')).all()
        for lang in languages:
            try:
                cur_l = LC.parse(lang.lang_code)
                lang.name = cur_l.get_language_name(get_locale())
            except UnknownLocaleError:
                lang.name = _(isoLanguages.get(part3=lang.lang_code).name)
        return languages 
Example #11
Source File: oauth_bb.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def github_login():
        if not github.authorized:
            return redirect(url_for('github.login'))
        account_info = github.get('/user')
        if account_info.ok:
            account_info_json = account_info.json()
            return bind_oauth_or_register(oauthblueprints[0]['id'], account_info_json['id'], 'github.login', 'github')
        flash(_(u"GitHub Oauth error, please retry later."), category="error")
        return redirect(url_for('web.login')) 
Example #12
Source File: oauth_bb.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def google_logged_in(blueprint, token):
        if not token:
            flash(_(u"Failed to log in with Google."), category="error")
            return False

        resp = blueprint.session.get("/oauth2/v2/userinfo")
        if not resp.ok:
            flash(_(u"Failed to fetch user info from Google."), category="error")
            return False

        google_info = resp.json()
        google_user_id = str(google_info["id"])
        return oauth_update_token(str(oauthblueprints[1]['id']), token, google_user_id) 
Example #13
Source File: oauth_bb.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def register_user_with_oauth(user=None):
    all_oauth = {}
    for oauth_key in oauth_check.keys():
        if str(oauth_key) + '_oauth_user_id' in session and session[str(oauth_key) + '_oauth_user_id'] != '':
            all_oauth[oauth_key] = oauth_check[oauth_key]
    if len(all_oauth.keys()) == 0:
        return
    if user is None:
        flash(_(u"Register with %(provider)s", provider=", ".join(list(all_oauth.values()))), category="success")
    else:
        for oauth_key in all_oauth.keys():
            # Find this OAuth token in the database, or create it
            query = ub.session.query(ub.OAuth).filter_by(
                provider=oauth_key,
                provider_user_id=session[str(oauth_key) + "_oauth_user_id"],
            )
            try:
                oauth_key = query.one()
                oauth_key.user_id = user.id
            except NoResultFound:
                # no found, return error
                return
            try:
                ub.session.commit()
            except Exception as e:
                log.exception(e)
                ub.session.rollback() 
Example #14
Source File: helper.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def delete_book_file(book, calibrepath, book_format=None):
    # check that path is 2 elements deep, check that target path has no subfolders
    if book.path.count('/') == 1:
        path = os.path.join(calibrepath, book.path)
        if book_format:
            for file in os.listdir(path):
                if file.upper().endswith("."+book_format):
                    os.remove(os.path.join(path, file))
            return True, None
        else:
            if os.path.isdir(path):
                if len(next(os.walk(path))[1]):
                    log.error("Deleting book %s failed, path has subfolders: %s", book.id, book.path)
                    return False , _("Deleting book %(id)s failed, path has subfolders: %(path)s",
                                     id=book.id,
                                     path=book.path)
                try:
                    for root, __, files in os.walk(path):
                        for f in files:
                            os.unlink(os.path.join(root, f))
                    shutil.rmtree(path)
                except (IOError, OSError) as e:
                    log.error("Deleting book %s failed: %s", book.id, e)
                    return False, _("Deleting book %(id)s failed: %(message)s", id=book.id, message=e)
                authorpath = os.path.join(calibrepath, os.path.split(book.path)[0])
                if not os.listdir(authorpath):
                    try:
                        shutil.rmtree(authorpath)
                    except (IOError, OSError) as e:
                        log.error("Deleting authorpath for book %s failed: %s", book.id, e)
                return True, None
            else:
                log.error("Deleting book %s failed, book path not valid: %s", book.id, book.path)
                return True, _("Deleting book %(id)s, book path not valid: %(path)s",
                                     id=book.id,
                                     path=book.path) 
Example #15
Source File: oauth_bb.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def bind_oauth_or_register(provider_id, provider_user_id, redirect_url, provider_name):
        query = ub.session.query(ub.OAuth).filter_by(
            provider=provider_id,
            provider_user_id=provider_user_id,
        )
        try:
            oauth_entry = query.first()
            # already bind with user, just login
            if oauth_entry.user:
                login_user(oauth_entry.user)
                log.debug(u"You are now logged in as: '%s'", oauth_entry.user.nickname)
                flash(_(u"you are now logged in as: '%(nickname)s'", nickname= oauth_entry.user.nickname),
                      category="success")
                return redirect(url_for('web.index'))
            else:
                # bind to current user
                if current_user and current_user.is_authenticated:
                    oauth_entry.user = current_user
                    try:
                        ub.session.add(oauth_entry)
                        ub.session.commit()
                        flash(_(u"Link to %(oauth)s Succeeded", oauth=provider_name), category="success")
                        return redirect(url_for('web.profile'))
                    except Exception as e:
                        log.exception(e)
                        ub.session.rollback()
                else:
                    flash(_(u"Login failed, No User Linked With OAuth Account"), category="error")
                log.info('Login failed, No User Linked With OAuth Account')
                return redirect(url_for('web.login'))
                # return redirect(url_for('web.login'))
                # if config.config_public_reg:
                #   return redirect(url_for('web.register'))
                # else:
                #    flash(_(u"Public registration is not enabled"), category="error")
                #    return redirect(url_for(redirect_url))
        except (NoResultFound, AttributeError):
            return redirect(url_for(redirect_url)) 
Example #16
Source File: charts.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def subtitle(self) -> str:
        return gettext('Stats') 
Example #17
Source File: about.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def subtitle(self) -> str:
        return gettext('About') 
Example #18
Source File: helper.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def convert_book_format(book_id, calibrepath, old_book_format, new_book_format, user_id, kindle_mail=None):
    book = calibre_db.get_book(book_id)
    data = calibre_db.get_book_format(book.id, old_book_format)
    if not data:
        error_message = _(u"%(format)s format not found for book id: %(book)d", format=old_book_format, book=book_id)
        log.error("convert_book_format: %s", error_message)
        return error_message
    if config.config_use_google_drive:
        df = gd.getFileFromEbooksFolder(book.path, data.name + "." + old_book_format.lower())
        if df:
            datafile = os.path.join(calibrepath, book.path, data.name + u"." + old_book_format.lower())
            if not os.path.exists(os.path.join(calibrepath, book.path)):
                os.makedirs(os.path.join(calibrepath, book.path))
            df.GetContentFile(datafile)
        else:
            error_message = _(u"%(format)s not found on Google Drive: %(fn)s",
                              format=old_book_format, fn=data.name + "." + old_book_format.lower())
            return error_message
    file_path = os.path.join(calibrepath, book.path, data.name)
    if os.path.exists(file_path + "." + old_book_format.lower()):
        # read settings and append converter task to queue
        if kindle_mail:
            settings = config.get_mail_settings()
            settings['subject'] = _('Send to Kindle')  # pretranslate Subject for e-mail
            settings['body'] = _(u'This e-mail has been sent via Calibre-Web.')
            # text = _(u"%(format)s: %(book)s", format=new_book_format, book=book.title)
        else:
            settings = dict()
        text = (u"%s -> %s: %s" % (old_book_format, new_book_format, book.title))
        settings['old_book_format'] = old_book_format
        settings['new_book_format'] = new_book_format
        worker.add_convert(file_path, book.id, user_id, text, settings, kindle_mail)
        return None
    else:
        error_message = _(u"%(format)s not found: %(fn)s",
                          format=old_book_format, fn=data.name + "." + old_book_format.lower())
        return error_message 
Example #19
Source File: template.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def render(self, engine: pystache.renderengine.RenderEngine, context: ContextStack) -> str:
        s = gettext(self.key)  # The key is populated in messages.pot via generate_translations.py - pylint: disable=translation-of-non-string
        def lookup(match: Match) -> str:
            return engine.fetch_string(context, match.group(1))
        s = re.sub(r'\{([a-z_]+)\}', lookup, s)
        return markdown(engine.escape(s), extensions=[NoParaTagsExtension()])

# pylint: disable=no-self-use 
Example #20
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def get_tasks_status():
    # if current user admin, show all email, otherwise only own emails
    tasks = worker.get_taskstatus()
    answer = render_task_status(tasks)
    return render_title_template('tasks.html', entries=answer, title=_(u"Tasks"), page="tasks") 
Example #21
Source File: report.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def TT_REPORT(self) -> str:
        return gettext('Report') 
Example #22
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def formats_list():
    if current_user.check_visibility(constants.SIDEBAR_FORMAT):
        entries = calibre_db.session.query(db.Data,
                                           func.count('data.book').label('count'),
                                           db.Data.format.label('format')) \
            .join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(db.Data.format).order_by(db.Data.format).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(),
                                     title=_(u"File formats list"), page="formatslist", data="formats")
    else:
        abort(404) 
Example #23
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def ratings_list():
    if current_user.check_visibility(constants.SIDEBAR_RATING):
        entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'),
                                   (db.Ratings.rating / 2).label('name')) \
            .join(db.books_ratings_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_ratings_link.rating')).order_by(db.Ratings.rating).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=list(),
                                     title=_(u"Ratings list"), page="ratingslist", data="ratings")
    else:
        abort(404) 
Example #24
Source File: report.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def TT_YOUR_DECK(self) -> str:
        return gettext('Your Deck') 
Example #25
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def publisher_list():
    if current_user.check_visibility(constants.SIDEBAR_PUBLISHER):
        entries = calibre_db.session.query(db.Publishers, func.count('books_publishers_link.book').label('count')) \
            .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(text('books_publishers_link.publisher')).order_by(db.Publishers.name).all()
        charlist = calibre_db.session.query(func.upper(func.substr(db.Publishers.name, 1, 1)).label('char')) \
            .join(db.books_publishers_link).join(db.Books).filter(calibre_db.common_filters()) \
            .group_by(func.upper(func.substr(db.Publishers.name, 1, 1))).all()
        return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist,
                                     title=_(u"Publishers"), page="publisherlist", data="publisher")
    else:
        abort(404) 
Example #26
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def render_category_books(page, book_id, order):
    name = calibre_db.session.query(db.Tags).filter(db.Tags.id == book_id).first()
    if name:
        entries, random, pagination = calibre_db.fill_indexpage(page,
                                                                db.Books,
                                                                db.Books.tags.any(db.Tags.id == book_id),
                                                                [order[0], db.Series.name, db.Books.series_index],
                                                                db.books_series_link, db.Series)
        return render_title_template('index.html', random=random, entries=entries, pagination=pagination, id=book_id,
                                     title=_(u"Category: %(name)s", name=name.name), page="category")
    else:
        abort(404) 
Example #27
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def render_formats_books(page, book_id, order):
    name = calibre_db.session.query(db.Data).filter(db.Data.format == book_id.upper()).first()
    if name:
        entries, random, pagination = calibre_db.fill_indexpage(page,
                                                                db.Books,
                                                                db.Books.data.any(db.Data.format == book_id.upper()),
                                                                [db.Books.timestamp.desc(), order[0]])
        return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id,
                                     title=_(u"File format: %(format)s", format=name.format), page="formats")
    else:
        abort(404) 
Example #28
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def render_ratings_books(page, book_id, order):
    name = calibre_db.session.query(db.Ratings).filter(db.Ratings.id == book_id).first()
    entries, random, pagination = calibre_db.fill_indexpage(page,
                                                            db.Books,
                                                            db.Books.ratings.any(db.Ratings.id == book_id),
                                                            [db.Books.timestamp.desc(), order[0]])
    if name and name.rating <= 10:
        return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id,
                                     title=_(u"Rating: %(rating)s stars", rating=int(name.rating / 2)), page="ratings")
    else:
        abort(404) 
Example #29
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def render_series_books(page, book_id, order):
    name = calibre_db.session.query(db.Series).filter(db.Series.id == book_id).first()
    if name:
        entries, random, pagination = calibre_db.fill_indexpage(page,
                                                                db.Books,
                                                                db.Books.series.any(db.Series.id == book_id),
                                                                [db.Books.series_index, order[0]])
        return render_title_template('index.html', random=random, pagination=pagination, entries=entries, id=book_id,
                                     title=_(u"Series: %(serie)s", serie=name.name), page="series")
    else:
        abort(404) 
Example #30
Source File: web.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def remote_login():
    auth_token = ub.RemoteAuthToken()
    ub.session.add(auth_token)
    ub.session.commit()

    verify_url = url_for('web.verify_token', token=auth_token.auth_token, _external=true)
    log.debug(u"Remot Login request with token: %s", auth_token.auth_token)
    return render_title_template('remote_login.html', title=_(u"login"), token=auth_token.auth_token,
                                 verify_url=verify_url, page="remotelogin")