def test_set_default_breadcrumb_root_different_from_blueprint_name(self):
        default_breadcrumb_root(self.foo, '.fooo')

        with self.app.test_client() as c:
            c.get('/foo/')
            self.assertEqual(current_path, 'breadcrumbs.fooo.bar')
            self.assertEqual(current_breadcrumbs[-1].url, '/foo/')

        with self.app.test_client() as c:
            c.get('/foo/baz')
            self.assertEqual(current_path, 'breadcrumbs.fooo.baz')
            self.assertEqual(current_breadcrumbs[-1].url, '/foo/baz')
    def test_template_context(self):
        default_breadcrumb_root(self.foo, 'breadcrumbs')

        with self.app.test_client() as c:
            response = c.get('/level3B')
            self.assertEqual(response.data.decode('utf8'),
                             'Test,/test;Level 2,/level2;Level 3B,/level3B;')

        with self.app.test_client() as c:
            response = c.get('/foo/baz')
            self.assertEqual(response.data.decode('utf8'),
                             'Test,/test;Baz,/foo/baz;')
Exemplo n.º 3
0
    def test_set_default_breadcrumb_root_as_dot(self):
        default_breadcrumb_root(self.foo, ".")

        with self.app.test_client() as c:
            c.get("/foo/")
            self.assertEqual(current_path, "breadcrumbs.bar")
            self.assertEqual(current_breadcrumbs[-1].url, "/foo/")

        with self.app.test_client() as c:
            c.get("/foo/baz")
            self.assertEqual(current_path, "breadcrumbs.baz")
            self.assertEqual(current_breadcrumbs[-1].url, "/foo/baz")
Exemplo n.º 4
0
    def test_set_default_breadcrumb_root_different_from_blueprint_name(self):
        default_breadcrumb_root(self.foo, ".fooo")

        with self.app.test_client() as c:
            c.get("/foo/")
            self.assertEqual(current_path, "breadcrumbs.fooo.bar")
            self.assertEqual(current_breadcrumbs[-1].url, "/foo/")

        with self.app.test_client() as c:
            c.get("/foo/baz")
            self.assertEqual(current_path, "breadcrumbs.fooo.baz")
            self.assertEqual(current_breadcrumbs[-1].url, "/foo/baz")
    def test_set_default_breadcrumb_root_as_dot(self):
        default_breadcrumb_root(self.foo, '.')

        with self.app.test_client() as c:
            c.get('/foo/')
            self.assertEqual(current_path, 'breadcrumbs.bar')
            self.assertEqual(current_breadcrumbs[-1].url, '/foo/')

        with self.app.test_client() as c:
            c.get('/foo/baz')
            self.assertEqual(current_path, 'breadcrumbs.baz')
            self.assertEqual(current_breadcrumbs[-1].url, '/foo/baz')
Exemplo n.º 6
0
    def test_template_context(self):
        default_breadcrumb_root(self.foo, "breadcrumbs")

        with self.app.test_client() as c:
            response = c.get("/level3B")
            self.assertEqual(
                response.data.decode("utf8"),
                "Test,/test;Level 2,/level2;Level 3B,/level3B;",
            )

        with self.app.test_client() as c:
            response = c.get("/foo/baz")
            self.assertEqual(response.data.decode("utf8"),
                             "Test,/test;Baz,/foo/baz;")
Exemplo n.º 7
0
    DepositionType,
    DraftDoesNotExists,
    FilenameAlreadyExists,
    ForbiddenAction,
    FormDoesNotExists,
    InvalidDepositionAction,
    InvalidDepositionType,
)
from ..signals import template_context_created
from ..storage import ChunkedDepositionStorage, DepositionStorage, ExternalFile, UploadError

blueprint = Blueprint(
    "webdeposit", __name__, url_prefix="/deposit", template_folder="../templates", static_folder="../static"
)

default_breadcrumb_root(blueprint, ".webdeposit")


def deposition_error_handler(endpoint=".index"):
    """Decorator to handle deposition exceptions."""

    def decorator(f):
        @wraps(f)
        def inner(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except InvalidDepositionType:
                if request.is_xhr:
                    abort(400)
                flash(_("Invalid deposition type."), "danger")
                return redirect(url_for(endpoint))
Exemplo n.º 8
0
from .forms import AttachTagForm, CreateTagForm, DetachTagForm, EditTagForm, \
    TagAnnotationForm, validate_tag_exists, validate_user_owns_tag, validators
from .models import WtgTAG, WtgTAGRecord, wash_tag

# Uset settings
user_settings = LocalProxy(lambda: current_user['settings'].get(
    'webtag', cfg['CFG_WEBTAG_DEFAULT_USER_SETTINGS']))

blueprint = Blueprint('webtag',
                      __name__,
                      url_prefix='/yourtags',
                      template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.tags')


@blueprint.route('/', methods=['GET', 'POST'])
@blueprint.route('/display', methods=['GET', 'POST'])
@blueprint.route('/display/cloud', methods=['GET', 'POST'])
@login_required
@templated('tags/display_cloud.html')
@register_menu(blueprint, 'personalize.tags', _('Your Tags'))
@register_breadcrumb(blueprint, '.', _('Your Tags'))
def display_cloud():
    """List of user's private/group/public tags."""
    user = User.query.get(current_user.get_id())
    tags = user.tags_query.order_by(WtgTAG.name).all()

    # Calculate document count for each tag
Exemplo n.º 9
0
    CreateTagForm,
    DetachTagForm,
    EditTagForm,
    TagAnnotationForm,
    validate_tag_exists,
    validate_user_owns_tag,
    validators,
)
from .models import WtgTAG, WtgTAGRecord, wash_tag

# Uset settings
user_settings = LocalProxy(lambda: current_user["settings"].get("webtag", cfg["CFG_WEBTAG_DEFAULT_USER_SETTINGS"]))

blueprint = Blueprint("webtag", __name__, url_prefix="/yourtags", template_folder="templates", static_folder="static")

default_breadcrumb_root(blueprint, ".webaccount.tags")


@blueprint.route("/", methods=["GET", "POST"])
@blueprint.route("/display", methods=["GET", "POST"])
@blueprint.route("/display/cloud", methods=["GET", "POST"])
@login_required
@templated("tags/display_cloud.html")
@register_menu(blueprint, "personalize.tags", _("Your Tags"))
@register_breadcrumb(blueprint, ".", _("Your Tags"))
def display_cloud():
    """List of user's private/group/public tags."""
    user = User.query.get(current_user.get_id())
    tags = user.tags_query.order_by(WtgTAG.name).all()

    # Calculate document count for each tag
Exemplo n.º 10
0
from it680vizapp import mysql, mail, serialize
from flask_mail import Message
#from mysql import escape_string as thwart
from flask import current_app
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root
import pandas as pd
import json
#from wapy.api import Wapy
#from walmart_api_client import WalmartApiClient
import pandas.io.sql as psql

from itsdangerous import URLSafeTimedSerializer, SignatureExpired

#Site blue print
mod = Blueprint('site', __name__, template_folder='templates', static_url_path='/site/static', static_folder='./static')
default_breadcrumb_root(mod, '.')


#Index route 
@mod.route('/')
# @register_breadcrumb(mod, '.', 'Home')
def index():
	return render_template('site/viz.html')

#Site homepage route
@mod.route('/home')
@register_breadcrumb(mod, '.', 'Home', order=0)
def home():
	return render_template('site/viz.html')

Exemplo n.º 11
0
from flask import Blueprint
from flask_breadcrumbs import default_breadcrumb_root

board_mod = Blueprint('dashboard', __name__, url_prefix='/dashboard')

default_breadcrumb_root(board_mod, '.')

import app.dashboard.views
Exemplo n.º 12
0
# You should have received a copy of the GNU Affero General Public License
# along with WebPsi.  If not, see <https://www.gnu.org/licenses/>.

from flask import Flask
from flask_breadcrumbs import Breadcrumbs, default_breadcrumb_root
from flask_sockets import Sockets
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler

from webpsi.views import home, classic_reg, singlebit_pk

app = Flask(__name__)
sockets = Sockets(app)

Breadcrumbs(app)
default_breadcrumb_root(home.blueprint, '.')

app.register_blueprint(home.blueprint)

app.register_blueprint(classic_reg.blueprint, url_prefix='/classic_reg')
sockets.register_blueprint(classic_reg.ws_blueprint, url_prefix='/classic_reg')

app.register_blueprint(singlebit_pk.blueprint, url_prefix='/singlebit_pk')
sockets.register_blueprint(singlebit_pk.ws_blueprint,
                           url_prefix='/singlebit_pk')

server = pywsgi.WSGIServer(('0.0.0.0', 58700),
                           application=app,
                           handler_class=WebSocketHandler)
server.serve_forever()
Exemplo n.º 13
0
    get_plugins,
    markCPEs,
    plugManager,
    pluginArgs,
    generate_full_query,
)
from ..helpers.server_side_datatables import ServerSideDataTable
from ..run import app

logging.setLoggerClass(AppLogger)

logger = logging.getLogger(__name__)

DATATABLE_FILTER = defaultFilters

default_breadcrumb_root(home, ".")

dbh = DatabaseHandler()


@home.route("/", methods=["GET"])
@register_breadcrumb(home, ".", "Home")
def index():
    return render_template("index.html", **config_args)


def view_vendor_name(*args, **kwargs):

    try:
        return [
            {
Exemplo n.º 14
0
from invenio.modules.search.models import Collection
from invenio.modules.search.signals import record_viewed
from invenio.utils import apache
from .api import get_record
from .models import Record as Bibrec
from .utils import references_nb_counts, citations_nb_counts, \
    visible_collection_tabs

blueprint = Blueprint('record',
                      __name__,
                      url_prefix="/" + CFG_SITE_RECORD,
                      static_url_path='/record',
                      template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, 'breadcrumbs.record')


def request_record(f):
    """Perform standard operation to check record availability for user."""
    @wraps(f)
    def decorated(recid, *args, **kwargs):
        from invenio.modules.access.mailcookie import \
            mail_cookie_create_authorize_action
        from invenio.modules.access.local_config import VIEWRESTRCOLL
        from invenio.legacy.search_engine import \
            guess_primary_collection_of_a_record, \
            check_user_can_view_record
        from invenio.b2share.modules.main.utils import check_fresh_record
        # ensure recid to be integer
        recid = int(recid)
from flask_login import current_user, login_required, login_user, logout_user
from flask_mongoengine.pagination import Pagination
from mongoengine.errors import NotUniqueError
import phonenumbers
# bandz modules
from bandz.models.entities import Band, Towns, User, Phone, Contact, Links, Email, BandMember, Assets
from bandz.manage.forms import CreateUpdateBandForm, CreateBandForm1, CreateBandForm2, CreateBandForm3, CreateBandForm4
from bandz.utils.gns import nav
from bandz.api.routes import list_genres
from bandz.utils.helpers import *

# MANAGE const
manage = Blueprint(
    'manage', __name__,
    url_prefix='/manage')  # import_name , usually the current module
default_breadcrumb_root(manage, '.public')
PER_PAGE = 10
ALPHABET = 'abcdefghijklmnopqrstuvwxyz1'


# dynamic list constructor for MANAGE breadcrumbs
def view_manage_dlc(*args, **kwargs):
    if request.referrer and request.referrer != request.url_root:
        referrer = request.referrer.replace(request.url_root, '')
        referrer = referrer.split("/", 5) if len(referrer) > 0 else ['mhome']
        #print(referrer)
        if referrer[0] == 'mhome':
            return [{'text': 'Manage My Bands'}]
        if len(referrer) > 2:
            band_view = 'recent' if (
                referrer[2] == 'recent' or referrer[2] == '') and (
Exemplo n.º 16
0
from flask_nav.elements import Navbar, Subgroup, View
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, RadioField
from wtforms.validators import DataRequired, ValidationError
from mongoengine.queryset import QuerySet
from mongoengine.queryset.visitor import Q, QNode
from flask_mongoengine.pagination import Pagination
# bandz modules
from bandz.utils.gns import nav
from bandz.models.entities import Band, Towns
from bandz.public.forms import SearchForm
from bandz.api.routes import list_genres, list_provinces
from bandz.utils.helpers import *
# const for PUBLIC module/routes
public = Blueprint('public', __name__)
default_breadcrumb_root(public, '.')
_AND = QNode.AND
_OR = QNode.OR
ALPHABET = 'abcdefghijklmnopqrstuvwxyz1'
SAMPLE_SIZE = 12
PAGE = 1
PER_PAGE = SAMPLE_SIZE


def band_dlc(*args, **kwargs):
    bname = request.view_args['bname'] if 'bname' in request.view_args else None
    letter = request.args.get(
        'letter') if 'letter' in request.args else de_article(bname)[0]
    if request.referrer and request.referrer != request.url_root:
        referrer = request.referrer.replace(
            request.url_root,
Exemplo n.º 17
0
from ..acl import viewholdingpen
from ..api import continue_oid_delayed, start_delayed
from ..models import BibWorkflowObject, ObjectVersion, Workflow
from ..registry import actions, workflows
from ..utils import (extract_data, get_action_list,
                     get_formatted_holdingpen_object,
                     get_holdingpen_objects,
                     get_previous_next_objects,
                     get_rendered_task_results,
                     sort_bwolist)

blueprint = Blueprint('compliance', __name__, url_prefix="/compliance",
                      template_folder='../templates',
                      static_folder='../static')

default_breadcrumb_root(blueprint, '.compliance')


@blueprint.route('/', methods=['GET', 'POST'])
@blueprint.route('/index', methods=['GET', 'POST'])
@register_menu(blueprint, 'personalize.compliance', _('Your Pending Actions'))
@register_breadcrumb(blueprint, '.', _('Holdingpen'))
@templated('workflows/index.html')
def index():
    """
    Display main interface of Holdingpen.

    Acts as a hub for catalogers (may be removed)
    """
    # FIXME: Add user filtering
    return dict(test="aaa")
Exemplo n.º 18
0
from flask import (Blueprint, current_app, flash, make_response, redirect,
                   render_template, request, url_for)
from flask_breadcrumbs import default_breadcrumb_root, register_breadcrumb
from flask_login import login_required
from flask_menu import register_menu

from invenio_base.i18n import _

from .config import CLOUDCONNECTOR_SERVICE_NAME_MAPPING
from .errors import CloudRedirectUrl
from .utils import _build_filesystem, _build_page

blueprint = Blueprint('cloudutils', __name__, url_prefix="/cloud",
                      template_folder='templates', static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.cloudconnector')


@blueprint.errorhandler(CloudRedirectUrl)
def connect_cloud(error):
    """Connect to the service."""
    url, service = error
    service = service.split('.')[-1]
    prompt = _('Click <a href="%(url)s">here</a> to connect your account'
               ' with %(service)s.',
               url=url,
               service=CLOUDCONNECTOR_SERVICE_NAME_MAPPING.get(service))
    flash(prompt, 'info')
    return redirect(url_for('.index'))

Exemplo n.º 19
0
    create_event,
    get_event,
    update_event,
    remove_event,
)

from forms import LoginForm, EventForm, TicketForm
from models import db
from utils import (
    view_event_dlc,
    upload_photo,
    ticket_already_added,
)

web = Blueprint('web', __name__, template_folder='templates', url_prefix='/')
default_breadcrumb_root(web, '.')


@web.route('/', methods=['get'])
@register_breadcrumb(web, '.', 'Groovin')
def index():
    return redirect(url_for('web.events'))


@web.route('/events', methods=['get'])
@login_required
@register_breadcrumb(web, '.events', 'Os Meus Eventos')
def events():
    return render_template('events/index.html')

Exemplo n.º 20
0
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

from flask import Blueprint, render_template
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root
from flask_babel import _

tweets = Blueprint('tweets', __name__, url_prefix='/tweets')
default_breadcrumb_root(tweets, '.')


@tweets.route('/list', methods=['GET'])
@register_breadcrumb(tweets, '.users.tweets', _('List Tweets'))
def tweets_list():
    return render_template('tweets/list.html', title=_("List Tweets"))


@tweets.route('/export', methods=['GET'])
@register_breadcrumb(tweets, '.users.tweets.list', _('Export tweets'))
def tweets_export():
    return render_template('tweets/export.html', title=_("Export tweets"))
Exemplo n.º 21
0
from invenio.ext.sqlalchemy import db
from invenio.modules.accounts.errors import AccountSecurityError, \
    IntegrityUsergroupError
from invenio.modules.accounts.models import User, Usergroup, UserUsergroup, \
    get_groups_user_not_joined

from forms import JoinUsergroupForm, UsergroupForm, UserJoinGroupForm
from config import GROUPS_AUTOCOMPLETE_LIMIT

blueprint = Blueprint('webgroup',
                      __name__,
                      url_prefix="/yourgroups",
                      template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, '.settings.groups')


@blueprint.route('/')
@blueprint.route('/index')
@register_menu(blueprint,
               'settings.groups',
               _('%(icon)s Groups', icon='<i class="fa fa-group fa-fw"></i>'),
               order=0,
               active_when=lambda: request.endpoint.startswith("webgroup."))
@register_breadcrumb(blueprint, '.', _('Groups'))
@login_required
@permission_required('usegroups')
def index():
    """List all user groups."""
    uid = current_user.get_id()
Exemplo n.º 22
0
from invenio.config import CFG_SITE_RECORD
from invenio.ext.template.context_processor import \
    register_template_context_processor
from invenio.modules.search.models import Collection
from invenio.modules.search.signals import record_viewed
from invenio.utils import apache
from .api import get_record
from .models import Record as Bibrec
from .utils import references_nb_counts, citations_nb_counts, \
    visible_collection_tabs

blueprint = Blueprint('record', __name__, url_prefix="/" + CFG_SITE_RECORD,
                      static_url_path='/record', template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, 'breadcrumbs.record')


def request_record(f):
    """Perform standard operation to check record availability for user."""
    @wraps(f)
    def decorated(recid, *args, **kwargs):
        from invenio.modules.access.mailcookie import \
            mail_cookie_create_authorize_action
        from invenio.modules.access.local_config import VIEWRESTRCOLL
        from invenio.legacy.search_engine import \
            guess_primary_collection_of_a_record, \
            check_user_can_view_record
        from invenio.b2share.modules.main.utils import check_fresh_record
        # ensure recid to be integer
        recid = int(recid)
Exemplo n.º 23
0
        """Return static file."""
        try:
            return super(self.__class__, self).send_static_file(filename)
        except:
            cache_timeout = self.get_send_file_max_age(filename)
            return send_from_directory(
                os.path.join(current_app.instance_path, "docs", "static"),
                filename,
                cache_timeout=cache_timeout)


blueprint = DocsBlueprint('documentation', __name__,
                          url_prefix="/documentation",
                          template_folder='templates', static_folder='static')

default_breadcrumb_root(blueprint, '.documentation')


@blueprint.route('/', strict_slashes=True)
@blueprint.route('/<path:docname>')
@register_menu(blueprint, 'main.documentation', _('Help'), order=99)
@register_breadcrumb(blueprint, '.', _('Help'))
def index(docname=None):
    """Render documentation page."""
    try:
        document = blueprint.support.get_document(
            docname or cfg["DOCUMENTATION_INDEX"])
    except DocumentNotFoundError:
        abort(404)
    additional_breadcrumbs = [{'text': document['title'],
                               'url': url_for('.index', docname=docname)}]
Exemplo n.º 24
0
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

"""Knowledge Flask Blueprint."""

from flask import Blueprint
from flask_breadcrumbs import default_breadcrumb_root


blueprint = Blueprint('knowledge', __name__, url_prefix="/kb",
                      template_folder='templates', static_folder='static')

default_breadcrumb_root(blueprint, '.settings.knowledge')
Exemplo n.º 25
0
from datetime import datetime

from flask import current_app, render_template, Blueprint, request, redirect
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root

from .models import Request, Link
import re

main_blueprint = Blueprint('main', __name__)
default_breadcrumb_root(main_blueprint, '.')


@main_blueprint.route('/')
@register_breadcrumb(main_blueprint, '.', 'Home')
def index():
    return render_template('index.html')


@main_blueprint.route('/l/<string:route>')
@register_breadcrumb(main_blueprint, '.link', 'Missing Link')
def link(route: str):
    """Performs a check on the given route, determining whether an active link
    with that route exists. Collects data on the particular request. If an
    appropriate link exists, redirect to the appropriate url.

    Args:
        route (str): the route requested.
    """

    start_time = datetime.now()
    link = Link.active_with_link(route, include_expiration=True).first()
Exemplo n.º 26
0
# A blueprint needs to be a package. That's why all folders needs to have a __init__.py
from flask import Blueprint
from flask_breadcrumbs import default_breadcrumb_root

blueprint_main = Blueprint('blueprint_main', __name__)
default_breadcrumb_root(blueprint_main, '.')
Exemplo n.º 27
0
import bleach
from flask import Blueprint, render_template, flash, redirect, url_for, request, current_app, send_from_directory, \
    jsonify
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root
from flask_login import login_required, current_user
from markupsafe import Markup
from werkzeug.utils import secure_filename

from app.blueprints.catalog.forms import ItemForm, UploadForm
from app.blueprints.catalog.models import Category, Item
from app.extensions import csrf
from app.mixins.util_wtforms import choices_from_dict
from config.settings import ITEMS_PER_PAGE

catalog = Blueprint('catalog', __name__, template_folder='templates')
default_breadcrumb_root(catalog, '.')


# noinspection PyUnusedLocal
def view_catalog_dlc(*args, **kwargs):
    if 'category' in request.view_args:
        category = request.view_args['category']
        return [{
            'text': 'Catalog',
            'url': url_for('catalog.home')
        }, {
            'text': category,
            'url': url_for('catalog.home', category=category)
        }]
    else:
        return [{'text': 'Catalog', 'url': url_for('catalog.home')}]
    DepositionType, DraftDoesNotExists, FilenameAlreadyExists, \
    ForbiddenAction, FormDoesNotExists, InvalidDepositionAction, \
    InvalidDepositionType
from ..signals import template_context_created
from ..storage import ChunkedDepositionStorage, DepositionStorage, \
    ExternalFile, UploadError

blueprint = Blueprint(
    'webdeposit',
    __name__,
    url_prefix='/deposit',
    template_folder='../templates',
    static_folder='../static'
)

default_breadcrumb_root(blueprint, '.webdeposit')


def deposition_error_handler(endpoint='.index'):
    """Decorator to handle deposition exceptions."""
    def decorator(f):
        @wraps(f)
        def inner(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except InvalidDepositionType:
                if request.is_xhr:
                    abort(400)
                flash(_("Invalid deposition type."), 'danger')
                return redirect(url_for(endpoint))
            except (DepositionDoesNotExists,):
Exemplo n.º 29
0
            return super(self.__class__, self).send_static_file(filename)
        except:
            cache_timeout = self.get_send_file_max_age(filename)
            return send_from_directory(os.path.join(current_app.instance_path,
                                                    "docs", "static"),
                                       filename,
                                       cache_timeout=cache_timeout)


blueprint = DocsBlueprint('documentation',
                          __name__,
                          url_prefix="/documentation",
                          template_folder='templates',
                          static_folder='static')

default_breadcrumb_root(blueprint, '.documentation')


@blueprint.route('/', strict_slashes=True)
@blueprint.route('/<path:docname>')
@register_menu(blueprint, 'main.documentation', _('Help'), order=99)
@register_breadcrumb(blueprint, '.', _('Help'))
def index(docname=None):
    """Render documentation page."""
    try:
        document = blueprint.support.get_document(
            docname or cfg["DOCUMENTATION_INDEX"])
    except DocumentNotFoundError:
        abort(404)
    additional_breadcrumbs = [{
        'text': document['title'],
Exemplo n.º 30
0
from ..utils import (
    alert_response_wrapper,
    extract_data,
    get_action_list,
    get_formatted_holdingpen_object,
    get_holdingpen_objects,
    get_previous_next_objects,
    get_rendered_task_results,
    sort_bwolist,
)

blueprint = Blueprint('holdingpen', __name__, url_prefix="/admin/holdingpen",
                      template_folder='../templates',
                      static_folder='../static')

default_breadcrumb_root(blueprint, '.holdingpen')
HOLDINGPEN_WORKFLOW_STATES = {
    ObjectVersion.HALTED: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.HALTED)),
        'class': 'danger'
    },
    ObjectVersion.WAITING: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.WAITING)),
        'class': 'warning'
    },
    ObjectVersion.ERROR: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.ERROR)),
        'class': 'danger'
    },
    ObjectVersion.COMPLETED: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.COMPLETED)),
Exemplo n.º 31
0
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

from flask import Blueprint, render_template
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root
from flask_babel import _
from flask import request, redirect, url_for, make_response, send_file, Response

from webapp.home.models import StudyDAO
from webapp.users.forms import Filter, Exclude, Save, downloadForm
from webapp.users.models import UserDAO
from twunet.tweets import TweetDAO
from webapp.users.models import ExcludedUsers, ExcludedUsersDAO, savedFiltersAndExclusions, savedFiltersAndExclusionsDAO
import math, re
users = Blueprint('users', __name__, url_prefix='/users')
default_breadcrumb_root(users, '.')

filename = "../../web-app/webapp/static/usernames.txt"
usersList = []


def include_user(name, profile):
    """
    Decide whether to include a user or not
    :param name: Name, screen name or location of the user
    :param profile: Profile in which we have to check whether the name exists
    :return: Boolean value true or false
    """
    if ((name in profile.name.lower()) or (name in profile.screen_name.lower())
            or (name in profile.location.lower())):
        return True
Exemplo n.º 32
0
        dbquery.update_user_inbox_for_reminders(uid)
        unread = db.session.query(db.func.count(UserMsgMESSAGE.id_msgMESSAGE)).\
            filter(db.and_(
                UserMsgMESSAGE.id_user_to == uid,
                UserMsgMESSAGE.status == cfg[
                    'CFG_WEBMESSAGE_STATUS_CODE']['NEW']
            )).scalar()
        return render_template_to_string(
            "messages/menu_item.html", unread=unread)

not_guest = lambda: not current_user.is_guest

blueprint = Blueprint('webmessage', __name__, url_prefix="/yourmessages",
                      template_folder='templates', static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.messages')


@blueprint.route('/menu', methods=['GET'])
# FIXME if request is_xhr then do not return 401
#@login_required
#@permission_required('usemessages')
#@templated('messages/menu.html')
def menu():
    uid = current_user.get_id()

    dbquery.update_user_inbox_for_reminders(uid)
    # join: msgMESSAGE -> user_msgMESSAGE, msgMESSAGE -> users
    # filter: all messages from user AND filter form
    # order: sorted by one of the table column
    messages = db.session.query(MsgMESSAGE, UserMsgMESSAGE).\
Exemplo n.º 33
0
from flask_menu import register_menu

from invenio.base.i18n import _
from invenio.modules.cloudconnector.utils import (_build_filesystem,
                                                  _build_page)

from .config import CLOUDCONNECTOR_SERVICE_NAME_MAPPING
from .errors import CloudRedirectUrl

blueprint = Blueprint('cloudutils',
                      __name__,
                      url_prefix="/cloud",
                      template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.cloudconnector')


@blueprint.errorhandler(CloudRedirectUrl)
def connect_cloud(error):
    """Connect to the service."""
    url, service = error
    service = service.split('.')[-1]
    prompt = _(
        'Click <a href="%(url)s">here</a> to connect your account'
        ' with %(service)s.',
        url=url,
        service=CLOUDCONNECTOR_SERVICE_NAME_MAPPING.get(service))
    flash(prompt, 'info')
    return redirect(url_for('.index'))
Exemplo n.º 34
0
    extract_data,
    get_action_list,
    get_formatted_holdingpen_object,
    get_holdingpen_objects,
    get_previous_next_objects,
    get_rendered_task_results,
    sort_bwolist,
)

blueprint = Blueprint('holdingpen',
                      __name__,
                      url_prefix="/admin/holdingpen",
                      template_folder='../templates',
                      static_folder='../static')

default_breadcrumb_root(blueprint, '.holdingpen')
HOLDINGPEN_WORKFLOW_STATES = {
    ObjectVersion.HALTED: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.HALTED)),
        'class': 'danger'
    },
    ObjectVersion.WAITING: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.WAITING)),
        'class': 'warning'
    },
    ObjectVersion.ERROR: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.ERROR)),
        'class': 'danger'
    },
    ObjectVersion.COMPLETED: {
        'message': _(ObjectVersion.name_from_version(ObjectVersion.COMPLETED)),
Exemplo n.º 35
0
                UserMsgMESSAGE.id_user_to == uid,
                UserMsgMESSAGE.status == cfg['CFG_WEBMESSAGE_STATUS_CODE']['NEW']
            )).scalar()
        return render_template_to_string("messages/menu_item.html",
                                         unread=unread)


not_guest = lambda: not current_user.is_guest

blueprint = Blueprint('webmessage',
                      __name__,
                      url_prefix="/yourmessages",
                      template_folder='templates',
                      static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.messages')


@blueprint.route('/menu', methods=['GET'])
#FIXME if request is_xhr then do not return 401
#@login_required
#@permission_required('usemessages')
#@templated('messages/menu.html')
def menu():
    uid = current_user.get_id()

    dbquery.update_user_inbox_for_reminders(uid)
    # join: msgMESSAGE -> user_msgMESSAGE, msgMESSAGE -> users
    # filter: all messages from user AND filter form
    # order: sorted by one of the table column
    messages = db.session.query(MsgMESSAGE, UserMsgMESSAGE).\
Exemplo n.º 36
0
from invenio.modules.search.signals import record_viewed
from invenio.utils import apache
from .api import get_record
from .models import Record as Bibrec
from .utils import references_nb_counts, citations_nb_counts, visible_collection_tabs

blueprint = Blueprint(
    "record",
    __name__,
    url_prefix="/" + CFG_SITE_RECORD,
    static_url_path="/record",
    template_folder="templates",
    static_folder="static",
)

default_breadcrumb_root(blueprint, ".")


def request_record(f):
    """Perform standard operation to check record availability for user."""

    @wraps(f)
    def decorated(recid, *args, **kwargs):
        from invenio.modules.access.mailcookie import mail_cookie_create_authorize_action
        from invenio.modules.access.local_config import VIEWRESTRCOLL
        from invenio.legacy.search_engine import guess_primary_collection_of_a_record, check_user_can_view_record

        # ensure recid to be integer
        recid = int(recid)
        g.collection = collection = Collection.query.filter(
            Collection.name == guess_primary_collection_of_a_record(recid)
Exemplo n.º 37
0
from invenio.base.i18n import _
from invenio.ext.principal import permission_required
from invenio.ext.sqlalchemy import db
from invenio.modules.accounts.errors import AccountSecurityError, \
    IntegrityUsergroupError
from invenio.modules.accounts.models import User, Usergroup, UserUsergroup, \
    get_groups_user_not_joined

from forms import JoinUsergroupForm, UsergroupForm, UserJoinGroupForm
from config import GROUPS_AUTOCOMPLETE_LIMIT


blueprint = Blueprint('webgroup', __name__, url_prefix="/yourgroups",
                      template_folder='templates', static_folder='static')

default_breadcrumb_root(blueprint, '.settings.groups')


@blueprint.route('/')
@blueprint.route('/index')
@register_menu(
    blueprint, 'settings.groups',
    _('%(icon)s Groups', icon='<i class="fa fa-group fa-fw"></i>'),
    order=0,
    active_when=lambda: request.endpoint.startswith("webgroup.")
)
@register_breadcrumb(blueprint, '.', _('Groups'))
@login_required
@permission_required('usegroups')
def index():
    """List all user groups."""
Exemplo n.º 38
0
from flask import Blueprint, render_template, url_for, redirect, flash, request
from flask_login import login_user, logout_user, login_required
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root

from .models import User
from .forms import LoginForm, RegistrationForm

auth_blueprint = Blueprint('auth', __name__, url_prefix='/auth')
default_breadcrumb_root(auth_blueprint, '.')


@auth_blueprint.route('/profile', methods=['GET'])
@register_breadcrumb(auth_blueprint, '.profile', 'Profile')
def profile():
    return render_template('auth/profile.html')


@auth_blueprint.route('/register', methods=['GET', 'POST'])
@register_breadcrumb(auth_blueprint, '.register', 'Register')
def register():
    form = RegistrationForm(request.form)
    if form.validate_on_submit():
        user = User(username=form.username.data,
                    email=form.email.data,
                    password=form.password.data)
        user.save()
        login_user(user)
        flash('Registration successful. You are logged in.', 'success')
        return redirect(url_for("main.index"))
    elif form.is_submitted():
        flash('The given data was invalid.', 'danger')
Exemplo n.º 39
0
from flask import Blueprint, render_template, flash, url_for, redirect
from flask_login import login_required, current_user
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root

settings_blueprint = Blueprint('settings', __name__, url_prefix='/settings')
default_breadcrumb_root(settings_blueprint, '.')


@settings_blueprint.route('/', methods=['GET'])
@register_breadcrumb(settings_blueprint, '.settings', 'Settings')
def index():
    return render_template('settings/index.html')


@settings_blueprint.before_request
@login_required
def before_request():
    """Function performed before any request related to this breadcrumb.
    Stops the user from continuing if they aren't currently authenticated.
    """
    if current_user.is_admin is False:
        flash('You need to be an admin to access this page.', 'danger')
        return redirect(url_for('main.index'))
Exemplo n.º 40
0
    dropWhitelist,
    importWhitelist,
    exportWhitelist,
    removeWhitelist,
    updateWhitelist,
)
from web.home.utils import adminInfo, addCPEToList

from . import admin
from ..run import app, plugins

config = Configuration()

dbh = DatabaseHandler()

default_breadcrumb_root(admin, ".Admin")


@admin.route("/")
@register_breadcrumb(admin, ".", "Admin")
@login_required
def admin_home():

    enabled_plugins = [x.identifier for x in list(get_enabled_plugins())]

    return render_template("admin.html",
                           status="default",
                           **adminInfo(),
                           plugins=get_all_plugins(),
                           enabled_plugins=enabled_plugins,
                           disable_pwd_section=config.useOIDC())
Exemplo n.º 41
0
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

from flask import Blueprint, request, render_template
from flask_babel import _
from flask_breadcrumbs import register_breadcrumb, default_breadcrumb_root

from webapp.home.forms import NewStudyForm, DeleteStudyForm, ConnectStudyForm
from webapp.home.models import StudyDAO, Study

home = Blueprint('home', __name__, url_prefix='/')
default_breadcrumb_root(home, '.')


def __handle_new_study_form(new_study_form, info_messages, error_messages):
    """
    Method to handle a new form 
    
    :param new_study_form: a flask form variable
    :param info_messages: a list of messages to be displayed
    :param error_messages: list of error messages 
    :return: No return value
    """
    if new_study_form.register.data:
        StudyDAO.get_instance().save(Study.from_study_form(new_study_form))
        info_messages.append(_("New study {0} saved".format(new_study_form.name.data)))
Exemplo n.º 42
0
from werkzeug import LocalProxy

from .forms import AttachTagForm, CreateTagForm, DetachTagForm, EditTagForm, \
    TagAnnotationForm, validate_tag_exists, validate_user_owns_tag, validators
from .models import WtgTAG, WtgTAGRecord, wash_tag

# Uset settings
user_settings = LocalProxy(
    lambda:
    current_user['settings'].get('webtag',
                                 cfg['CFG_WEBTAG_DEFAULT_USER_SETTINGS']))

blueprint = Blueprint('webtag', __name__, url_prefix='/yourtags',
                      template_folder='templates', static_folder='static')

default_breadcrumb_root(blueprint, '.webaccount.tags')


@blueprint.route('/', methods=['GET', 'POST'])
@blueprint.route('/display', methods=['GET', 'POST'])
@blueprint.route('/display/cloud', methods=['GET', 'POST'])
@login_required
@templated('tags/display_cloud.html')
@register_menu(blueprint, 'personalize.tags', _('Your Tags'))
@register_breadcrumb(blueprint, '.', _('Your Tags'))
def display_cloud():
    """List of user's private/group/public tags."""
    user = User.query.get(current_user.get_id())
    tags = user.tags_query.order_by(WtgTAG.name).all()

    # Calculate document count for each tag
Exemplo n.º 43
0
from ..signals import template_context_created
from ..models import Deposition, DepositionType, \
    DepositionFile, InvalidDepositionType, DepositionDoesNotExists, \
    DraftDoesNotExists, FormDoesNotExists, DepositionNotDeletable, \
    DepositionDraftCacheManager, FilenameAlreadyExists, ForbiddenAction, \
    InvalidDepositionAction
from ..storage import ChunkedDepositionStorage, \
    DepositionStorage, ExternalFile, UploadError

blueprint = Blueprint('webdeposit',
                      __name__,
                      url_prefix='/deposit',
                      template_folder='../templates',
                      static_folder='../static')

default_breadcrumb_root(blueprint, '.webdeposit')


def deposition_error_handler(endpoint='.index'):
    """Decorator to handle deposition exceptions."""
    def decorator(f):
        @wraps(f)
        def inner(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except InvalidDepositionType:
                if request.is_xhr:
                    abort(400)
                flash(_("Invalid deposition type."), 'danger')
                return redirect(url_for(endpoint))
            except (DepositionDoesNotExists, ):
Exemplo n.º 44
0
from invenio.base.decorators import wash_arguments, templated
from invenio.ext.template.context_processor import \
    register_template_context_processor
from invenio_formatter import format_record
from invenio.modules.search.forms import EasySearchForm
from invenio.utils.text import slugify

from ..models import Collection

blueprint = Blueprint('collections', __name__, url_prefix='',
                      template_folder='../templates',
                      static_url_path='',  # static url path has to be empty
                                           # if url_prefix is empty
                      static_folder='../static')

default_breadcrumb_root(blueprint, '.')


@blueprint.route('/index.html', methods=['GET', 'POST'])
@blueprint.route('/index.py', methods=['GET', 'POST'])
@blueprint.route('/', methods=['GET', 'POST'])
@templated('search/index.html')
@register_menu(blueprint, 'main.collection', _('Search'), order=1)
@register_breadcrumb(blueprint, '.', _('Home'))
def index():
    """Render the homepage."""
    # legacy app support
    c = request.values.get('c')
    if c:
        warnings.warn("'c' argument for this url has been deprecated",
                      PendingDeprecationWarning)
Exemplo n.º 45
0
    cache = Cache()

from .api import get_schema_data, get_schemas, internal_schema_url

from .utils import split_path, tree_insert, tree_sort


blueprint = Blueprint(
    'jsonschemas',
    __name__,
    url_prefix='/jsonschemas',
    static_folder='static',
    template_folder='templates',
)

default_breadcrumb_root(blueprint, '.jsonschemas')


@blueprint.route('/', methods=['GET', 'POST'])
@register_breadcrumb(blueprint, '.', _('JSON Schemas'))
def index():
    """Render schema index with all known schema files."""
    tree = dict()
    for name in get_schemas():
        path = split_path(name)
        tree_insert(tree, path[:-1], {
            'name': name,
            'link': internal_schema_url(*path)
        })

    return render_template('jsonschemas/schema.html', tree=tree_sort(tree))