from flask import Blueprint, render_template, current_app, redirect, url_for, request blueprint = Blueprint( 'matrix_iframe', __name__, template_folder='templates', static_folder='static', static_url_path='/static/matrix_iframe', ) def init_app(app, server_url='', room_alias='', base_template='layout.html', login_endpoint=None): """ Register the Matrix chat blueprint with a Flask app. Args: server_url: Matrix homeserver base URL, e.g. "https://matrix.sticknife.com" room_alias: Matrix room alias, e.g. "#sticknife-library:matrix.sticknife.com" base_template: Jinja2 base template to extend, default "layout.html" login_endpoint: Flask endpoint to redirect unauthenticated users to, e.g. "web.login". If None, no auth guard is applied. """ app.config.setdefault('MATRIX_SERVER_URL', server_url) app.config.setdefault('MATRIX_ROOM_ALIAS', room_alias) app.config.setdefault('MATRIX_CHAT_BASE', base_template) app.config.setdefault('MATRIX_CHAT_LOGIN_ENDPOINT', login_endpoint) app.register_blueprint(blueprint) @blueprint.app_context_processor def _inject_matrix_chat(): """Makes matrix_chat_available=True visible to all templates when the blueprint is registered.""" return {'matrix_chat_available': True} @blueprint.before_request def _auth_guard(): login_endpoint = current_app.config.get('MATRIX_CHAT_LOGIN_ENDPOINT') if not login_endpoint: return try: from flask_login import current_user if not current_user.is_authenticated: return redirect(url_for(login_endpoint, next=request.url)) except ImportError: pass @blueprint.route('/chat') def chat(): return render_template( 'matrix_iframe/chat.html', matrix_server=current_app.config.get('MATRIX_SERVER_URL', ''), matrix_room_alias=current_app.config.get('MATRIX_ROOM_ALIAS', ''), base_template=current_app.config.get('MATRIX_CHAT_BASE', 'layout.html'), page='chat', )