Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions openlibrary/plugins/openlibrary/home.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
from infogami.utils.view import public, render_template
from openlibrary.core import admin, cache, ia, lending
from openlibrary.i18n import gettext as _
from openlibrary.plugins.upstream.utils import get_blog_feeds
from openlibrary.plugins.upstream.utils import (
convert_iso_to_marc,
get_blog_feeds,
get_populated_languages,
)
from openlibrary.plugins.worksearch import search, subjects
from openlibrary.utils import dateutil
from openlibrary.utils.async_utils import set_context_from_legacy_web_py
Expand Down Expand Up @@ -112,12 +116,19 @@ def GET(self):


@cache.memoize(
engine="memcache", key="home.random_book", expires=dateutil.HALF_HOUR_SECS
engine="memcache",
key=lambda count, language=None: f"home.random_book.{language or 'all'}",
expires=dateutil.HALF_HOUR_SECS,
)
def get_random_borrowable_ebook_keys(count: int) -> list[str]:
def get_random_borrowable_ebook_keys(
count: int, language: str | None = None
) -> list[str]:
solr = search.get_solr()
query = 'type:edition AND ebook_access:[borrowable TO *]'
if language:
query += f' AND language:{language}'
docs = solr.select(
'type:edition AND ebook_access:[borrowable TO *]',
query,
fields=['key'],
rows=count,
sort=f'random_{random.random()} desc',
Expand All @@ -129,7 +140,16 @@ class random_book(delegate.page):
path = "/random"

def GET(self):
keys = get_random_borrowable_ebook_keys(1000)
# Get user's language preference
user_lang = None
web_lang = web.ctx.lang or 'en'
marc_lang = convert_iso_to_marc(web_lang)

# Only filter by language if it's a populated language
if marc_lang and marc_lang in get_populated_languages():
user_lang = marc_lang

keys = get_random_borrowable_ebook_keys(1000, language=user_lang)
raise web.seeother(random.choice(keys))


Expand Down
Loading