Skip to content
Closed
114 changes: 72 additions & 42 deletions opac/webapp/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ def add_collection_to_g():

@main.before_app_request
def add_langs():
session["langs"] = current_app.config.get("LANGUAGES")
# Store available languages in g instead of session to avoid session cookie
g.langs = current_app.config.get("LANGUAGES")


@main.after_request
Expand All @@ -85,11 +86,8 @@ def add_header(response):
return response


@main.after_request
def add_language_code(response):
language = session.get("lang", get_locale())
response.set_cookie("language", language)
return response
# Removed add_language_code() to eliminate Set-Cookie: language header
# This allows CDN/Varnish to cache pages properly


@main.before_app_request
Expand All @@ -101,7 +99,7 @@ def add_forms_to_g():

@main.before_app_request
def add_scielo_org_config_to_g():
language = session.get("lang", get_locale())
language = get_locale()
scielo_org_links = {
# if language doesnt exists set the 'en' to SciELO ORG links.
key: url.get(language, "en")
Expand All @@ -112,55 +110,87 @@ def add_scielo_org_config_to_g():

@babel.localeselector
def get_locale():
"""
Determine language based on query parameter or Accept-Language header.
Does not use session/cookies to allow CDN/Varnish caching.
CDN can use Vary: Accept-Language for proper caching by language.
"""
# Cache the result in g to avoid repeated computation
if hasattr(g, 'lang'):
return g.lang

langs = current_app.config.get("LANGUAGES")

# Check for explicit language in query parameter (for language switcher)
lang_from_query = request.args.get('lang')
if lang_from_query and lang_from_query in langs:
g.lang = lang_from_query
return g.lang

# Fall back to Accept-Language header
lang_from_headers = request.accept_languages.best_match(list(langs.keys()))

if "lang" not in list(session.keys()):
session["lang"] = lang_from_headers

if not lang_from_headers and not session["lang"]:
# Caso não seja possível detectar o idioma e não tenhamos a chave lang
# no seção, fixamos o idioma padrão.
session["lang"] = current_app.config.get("BABEL_DEFAULT_LOCALE")

return session["lang"]

# Use detected language or fall back to default
if lang_from_headers:
g.lang = lang_from_headers
else:
g.lang = current_app.config.get("BABEL_DEFAULT_LOCALE", "pt_BR")

return g.lang


@main.route("/set_locale/<string:lang_code>/")
def set_locale(lang_code):
"""
Language switcher endpoint. Instead of storing in session/cookie,
redirects to the same page with ?lang= query parameter.
This allows language selection without cookies, enabling CDN caching.
"""
langs = current_app.config.get("LANGUAGES")

if lang_code not in list(langs.keys()):
abort(400, _("Código de idioma inválido"))

referrer = request.referrer
hash = request.args.get("hash")
if hash:
referrer += "#" + hash

# salvar o lang code na sessão
session["lang"] = lang_code
if referrer:
return redirect(referrer)
else:
return redirect("/")
if not referrer:
referrer = url_for('main.index')

# Parse the referrer URL to add/update lang parameter
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse
parsed = urlparse(referrer)
query_params = parse_qs(parsed.query)
query_params['lang'] = [lang_code]

# Handle hash fragment
hash_fragment = request.args.get("hash", "")

# Rebuild URL with updated query string
new_query = urlencode(query_params, doseq=True)
new_url = urlunparse((
parsed.scheme,
parsed.netloc,
parsed.path,
parsed.params,
new_query,
hash_fragment
))

return redirect(new_url)


def get_lang_from_session():
"""
Tenta retornar o idioma da seção, caso não consiga retorna
BABEL_DEFAULT_LOCALE.
Returns the current language. Updated to use get_locale() instead of session.
Kept for backward compatibility with existing code.
"""
try:
return session["lang"]
except KeyError:
return current_app.config.get("BABEL_DEFAULT_LOCALE")
return get_locale()



@main.route("/")
@cache.cached(key_prefix=cache_key_with_lang)
def index():
language = session.get("lang", get_locale())
language = get_locale()
news = controllers.get_latest_news_by_lang(language)

tweets = controllers.get_collection_tweets()
Expand Down Expand Up @@ -261,7 +291,7 @@ def collection_list_thematic():
@main.route("/journals/feed/")
@cache.cached(key_prefix=cache_key_with_lang)
def collection_list_feed():
language = session.get("lang", get_locale())
language = get_locale()
collection = controllers.get_current_collection()

title = "SciELO - %s - %s" % (
Expand Down Expand Up @@ -327,7 +357,7 @@ def collection_list_feed():
@main.route("/about/<string:slug_name>", methods=["GET"])
@cache.cached(key_prefix=cache_key_with_lang_with_qs)
def about_collection(slug_name=None):
language = session.get("lang", get_locale())
language = get_locale()

context = {}
page = None
Expand Down Expand Up @@ -486,7 +516,7 @@ def journal_detail(url_seg):
abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason))

# todo: ajustar para que seja só noticias relacionadas ao periódico
language = session.get("lang", get_locale())
language = get_locale()
news = controllers.get_latest_news_by_lang(language)

# Press releases
Expand Down Expand Up @@ -576,7 +606,7 @@ def journal_feed(url_seg):
subtitle=utils.get_label_issue(last_issue),
)

feed_language = session.get("lang", get_locale())
feed_language = get_locale()
feed_language = feed_language[:2].lower()

for article in articles:
Expand Down Expand Up @@ -607,7 +637,7 @@ def journal_feed(url_seg):
@main.route("/journal/<string:url_seg>/about/", methods=["GET"])
@cache.cached(key_prefix=cache_key_with_lang)
def about_journal(url_seg):
language = session.get("lang", get_locale())
language = get_locale()
journal = controllers.get_journal_by_url_seg(url_seg)
content = None

Expand Down Expand Up @@ -824,7 +854,7 @@ def issue_grid(url_seg):
abort(404, JOURNAL_UNPUBLISH + _(journal.unpublish_reason))

# idioma da sessão
language = session.get("lang", get_locale())
language = get_locale()

# A ordenação padrão da função ``get_issues_by_jid``: "-year", "-volume", "-order"
issues_data = controllers.get_issues_for_grid_by_jid(journal.id, is_public=True)
Expand Down Expand Up @@ -871,7 +901,7 @@ def issue_toc(url_seg, url_seg_issue):
filter_section_enable = bool(current_app.config["FILTER_SECTION_ENABLE"])

# idioma da sessão
language = session.get("lang", get_locale())
language = get_locale()

# obtém o issue
issue = controllers.get_issue_by_url_seg(url_seg, url_seg_issue)
Expand Down Expand Up @@ -1035,7 +1065,7 @@ def issue_feed(url_seg, url_seg_issue):
subtitle=utils.get_label_issue(issue),
)

feed_language = session.get("lang", get_locale())
feed_language = get_locale()

for article in articles:
# ######### TODO: Revisar #########
Expand Down
2 changes: 1 addition & 1 deletion opac/webapp/templates/admin/opac_base.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
<small>
{% for k,v in config.LANGUAGES.items() %}
<a href="{{ url_for('main.set_locale', lang_code=k) }}">
{% if k == session['lang'] %}
{% if k == g.lang %}
<strong>{{ v }}</strong>
{% else %}
{{ v }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ <h2 class="logo-svg">
</a>
</li>
<li>
<a href="{{ config.URL_SEARCH }}?q=*&lang={% if session.lang %}{{ session.lang[:2] }}{% endif %}&filter[in][]={{config.OPAC_COLLECTION}}">
<a href="{{ config.URL_SEARCH }}?q=*&lang={% if g.lang %}{{ g.lang[:2] }}{% endif %}&filter[in][]={{config.OPAC_COLLECTION}}">
Busca
</a>
</li>
Expand Down Expand Up @@ -143,7 +143,7 @@ <h2 class="logo-svg">
</ul>
</li>
<li>
<a target="_blank" href="{{ config.URL_BLOG_SCIELO }}/{{ session.lang }}/">
<a target="_blank" href="{{ config.URL_BLOG_SCIELO }}/{{ g.lang }}/">
<strong>Blog SciELO em Perspectiva</strong>
</a>
</li>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
<div class="card-body">
<div class="h6 card-subtitle mb-1">{% trans%}Volume{% endtrans %}: {{ article.issue.volume }} - {% trans%}Publicado em{% endtrans %}: {{ article.publication_date }}</div>

{% if session.lang %}
{% if g.lang %}

<strong class="card-title text-primary">
{{ article.get_title_by_lang(session.lang[:2])|default(_('Documento sem título'), true)|striptags|capitalize }}
{{ article.get_title_by_lang(g.lang[:2])|default(_('Documento sem título'), true)|striptags|capitalize }}
</strong>

{% endif %}
Expand Down
2 changes: 1 addition & 1 deletion opac/webapp/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ <h2 class="h4 modal-title">{% trans %}Mensagem{% endtrans %}</h2>
// Garante que o valor do campo share_url é a URL corrente.
$('#share_url').val(window.location.href);

//moment.locale('{{ session.lang }}');
//moment.locale('{{ g.lang }}');

//$("#date").text(moment().format("L HH:mm:ss ZZ"));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<div class="container">
<form class="visually-hidden" method="get" action="{{ config.URL_SEARCH }}" id="searchForm" name="searchForm">
<input type="hidden" name="q" id="q" value="">
<input type="hidden" name="lang" id="lang" value="{% if session.lang %}{{ session.lang[:2] }}{% endif %}">
<input type="hidden" name="lang" id="lang" value="{% if g.lang %}{{ g.lang[:2] }}{% endif %}">
<input type="hidden" name="filter[in][]" value="{{ config.OPAC_COLLECTION }}">
<button type="submit">Enviar</button>
</form>
Expand Down
6 changes: 3 additions & 3 deletions opac/webapp/templates/collection/includes/nav.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
</a>
</li>
<li>
<a href="{{ config.URL_SEARCH }}?q=*&lang={% if session.lang %}{{ session.lang[:2] }}{% endif %}&filter[in][]={{config.OPAC_COLLECTION}}">
<a href="{{ config.URL_SEARCH }}?q=*&lang={% if g.lang %}{{ g.lang[:2] }}{% endif %}&filter[in][]={{config.OPAC_COLLECTION}}">
{% trans %}Busca{% endtrans %}
</a>
</li>
Expand Down Expand Up @@ -117,10 +117,10 @@
</ul>
</li>
<li>
{% if session.lang == 'pt_BR' %}
{% if g.lang == 'pt_BR' %}
<a target="_blank" href="{{ config.URL_BLOG_SCIELO }}">
{% else %}
<a target="_blank" href="{{ config.URL_BLOG_SCIELO }}/{{ session.lang }}/">
<a target="_blank" href="{{ config.URL_BLOG_SCIELO }}/{{ g.lang }}/">
{% endif %}
<strong>{% trans %}Blog SciELO em Perspectiva{% endtrans %}</strong>
</a>
Expand Down
8 changes: 4 additions & 4 deletions opac/webapp/templates/includes/language.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<div class="dropdown">
<button type="button" class="btn btn-sm btn-secondary scielo__btn-with-icon--left dropdown-toggle mb-0 float-end mt-1" data-bs-toggle="dropdown" aria-expanded="false">
<span class="material-icons-outlined">language</span>
{% for lang_code, lang_name in session.langs.items() %}
{% for lang_code, lang_name in g.langs.items() %}

{% if session.lang == lang_code %}
{% if g.lang == lang_code %}
<span class="d-lg-none">{{lang_code}}</span>
<span class="d-none d-lg-block">{{lang_name}}</span>
{% endif %}
Expand All @@ -15,9 +15,9 @@
</button>
<ul class="dropdown-menu dropdown-menu-end">

{% for lang_code, lang_name in session.langs.items() %}
{% for lang_code, lang_name in g.langs.items() %}

{% if session.lang != lang_code %}
{% if g.lang != lang_code %}
<li><a class="dropdown-item" href="{{ url_for('.set_locale', lang_code=lang_code) }}" lang="{{lang_code}}">{{lang_name}}</a></li>
{% endif %}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ <h2 class="logo-svg-mini">
</ul>
</li>
<li>
<a href="{{ config.URL_SEARCH }}?q=*&lang={% if session.lang %}{{ session.lang[:2] }}{% endif %}&filter[journal_title][]={% if journal.title %}{{ journal.title }}{% endif %}" class="showTooltip" data-placement="bottom" title="{% trans %}Buscar{% endtrans %}">
<a href="{{ config.URL_SEARCH }}?q=*&lang={% if g.lang %}{{ g.lang[:2] }}{% endif %}&filter[journal_title][]={% if journal.title %}{{ journal.title }}{% endif %}" class="showTooltip" data-placement="bottom" title="{% trans %}Buscar{% endtrans %}">
<span class="glyphBtn search"></span>
</a>
</li>
Expand Down
2 changes: 1 addition & 1 deletion opac/webapp/templates/issue/includes/meta.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<meta property="og:url" content="{{ request.url }}" />
<meta property="og:type" content="website" />
<meta property="og:title" content="{{ journal.title }}" />
<meta property="og:description" content="{{ journal.get_mission_by_lang(session.lang[:2])|safe|default(_(" Periódico sem
<meta property="og:description" content="{{ journal.get_mission_by_lang(g.lang[:2])|safe|default(_(" Periódico sem
missão cadastrada"), true) }}" />
<meta property="og:image" content="{{ journal.logo_url|absolute_url(request.url_root) }}" />
<!-- social share tags -->
10 changes: 5 additions & 5 deletions opac/webapp/templates/issue/toc.html
Original file line number Diff line number Diff line change
Expand Up @@ -195,22 +195,22 @@ <h2 class="h4 d-none">
<tr>
<td class="pt-4 pb-4" data-date="{% if article.publication_date %}{{ article.publication_date.replace('-', '') }}{% endif %}">

{% if session.lang %}
{% with nova_variavel=article.get_section_by_lang(session.lang[:2])%}
{% if g.lang %}
{% with nova_variavel=article.get_section_by_lang(g.lang[:2])%}
<!-- Aqui você pode usar 'nova_variavel' -->
{% if nova_variavel %}
<span class="badge badge-info d-inline px-2 py-1 border-0">{{ nova_variavel | safe }}</span><br>
{% endif %}
{% endwith %}
<strong class="d-block mt-2">{{ article.get_title_by_lang(session.lang[:2])|default(_('Documento sem título'), true) | safe }}</strong>
<strong class="d-block mt-2">{{ article.get_title_by_lang(g.lang[:2])|default(_('Documento sem título'), true) | safe }}</strong>
<!-- publication_date: {{article.publication_date}} -->
<!-- PID: {{article.pid}} -->
{% endif %}

<!-- Autores --->
{%- for author in article.authors %}
{% if session.lang %}
<a class="me-2" href="{{config['URL_SEARCH']}}?lang={{session.lang[:2]}}&q=au:{{ author }}">{{- author|striptags -}}</a>
{% if g.lang %}
<a class="me-2" href="{{config['URL_SEARCH']}}?lang={{g.lang[:2]}}&q=au:{{ author }}">{{- author|striptags -}}</a>
{% else %}
<a class="me-2" href="{{config['URL_SEARCH']}}?q=au:{{ author }}">{{- author|striptags -}}</a>
{% if not loop.last %};{% endif %}
Expand Down
Loading