Skip to content
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,19 @@ Progression requirements can now reference the top of the prescribed range via t
this change.
* Sets with "Until Failure" or "Max Reps" but no repetitions value keep their
unit in the routine API and show it in the set text.
* The exercise and ingredient syncs no longer hang forever when the remote
server stops answering. Requests to it now time out, see
`WGER_REQUEST_TIMEOUT`.

## New settings
*(for self-hoster)*

* `CAPTCHA_PROVIDER` (`none`, `recaptcha` or `turnstile`) replaces `USE_RECAPTCHA`.
`USE_RECAPTCHA=True` keeps working for now, but `manage.py check` warns about
it. Turnstile needs `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY`.
* `WGER_REQUEST_TIMEOUT` (default `60`): seconds to wait for an answer from a
remote server, e.g. `WGER_INSTANCE` during the exercise and ingredient syncs,
before giving up.

## Breaking API changes
*(only relevant if you have your own scripts or interact with the REST API)*
Expand Down
1 change: 1 addition & 0 deletions settings/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
POWERSYNC_URL_PATH = env.str('POWERSYNC_URL_PATH', 'ps')
POWERSYNC_URL = env.str('POWERSYNC_URL', '')
POWERSYNC_TOKEN_LIFETIME = env.int('POWERSYNC_TOKEN_LIFETIME', 600)
WGER_REQUEST_TIMEOUT = env.int('WGER_REQUEST_TIMEOUT', 60)
if not DEBUG and any(
key and hashlib.sha256(key.encode()).hexdigest() in _DEFAULT_JWT_KEY_HASHES
for key in (JWT_PUBLIC_KEY, JWT_PRIVATE_KEY)
Expand Down
3 changes: 3 additions & 0 deletions settings/settings_global.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,9 @@ def jwk_b64_to_pem(b64_jwk_str: str):

USER_AGENTS_CACHE = 'default'

# Read timeout in seconds for requests to remote servers
WGER_REQUEST_TIMEOUT = 60

#
# Application specific configuration options
#
Expand Down
3 changes: 2 additions & 1 deletion wger/core/api/min_server_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@

# wger
from wger.core.api.endpoints import MIN_SERVER_VERSION_ENDPOINT
from wger.utils.requests import wger_request_timeout
from wger.utils.url import make_uri
from wger.version import VERSION


def check_min_server_version(remote_url):
url = make_uri(MIN_SERVER_VERSION_ENDPOINT, server_url=remote_url)
min_version = parse(requests.get(url).json())
min_version = parse(requests.get(url, timeout=wger_request_timeout()).json())

if min_version > VERSION:
raise CommandError(
Expand Down
3 changes: 3 additions & 0 deletions wger/core/tests/test_check_min_server_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

# wger
from wger.core.api.min_server_version import check_min_server_version
from wger.utils.requests import wger_request_timeout
from wger.version import VERSION


Expand All @@ -42,6 +43,8 @@ def test_version_ok(self, mock_get):
except CommandError:
self.fail('check_min_server_version raised CommandError unexpectedly!')

self.assertEqual(mock_get.call_args.kwargs.get('timeout'), wger_request_timeout())

@patch('wger.core.api.min_server_version.requests.get')
def test_version_too_low(self, mock_get):
mock_response = Mock()
Expand Down
9 changes: 7 additions & 2 deletions wger/exercises/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
get_all_paginated,
get_paginated,
wger_headers,
wger_request_timeout,
)
from wger.utils.url import make_uri

Expand Down Expand Up @@ -411,7 +412,9 @@ def download_exercise_images(
image.save()
except ExerciseImage.DoesNotExist:
print_fn(' Image not found in local DB, creating now...')
retrieved_image = requests.get(image_data['image'], headers=headers)
retrieved_image = requests.get(
image_data['image'], headers=headers, timeout=wger_request_timeout()
)
try:
ExerciseImage.from_json(exercise, retrieved_image, image_data)
except ValidationError as e:
Expand Down Expand Up @@ -462,7 +465,9 @@ def download_exercise_videos(

# Save the downloaded video
# http://stackoverflow.com/questions/1308386/programmatically-saving-image-to-
retrieved_video = requests.get(video_data['video'], headers=headers)
retrieved_video = requests.get(
video_data['video'], headers=headers, timeout=wger_request_timeout()
)

# Temporary files on Windows don't support the delete attribute
if os.name == 'nt':
Expand Down
25 changes: 22 additions & 3 deletions wger/exercises/tests/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@
WorkoutLog,
)
from wger.utils.cache import CacheKeyMapper
from wger.utils.requests import wger_headers
from wger.utils.requests import (
wger_headers,
wger_request_timeout,
)


def _valid_png_bytes():
Expand Down Expand Up @@ -733,6 +736,7 @@ def test_language_sync(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/language/',
headers=wger_headers(),
timeout=wger_request_timeout(),
)

# Assert
Expand All @@ -751,6 +755,7 @@ def test_license_sync(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/license/',
headers=wger_headers(),
timeout=wger_request_timeout(),
)
self.assertEqual(
License.objects.get(pk=1).url,
Expand All @@ -771,6 +776,7 @@ def test_categories_sync(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/exercisecategory/',
headers=wger_headers(),
timeout=wger_request_timeout(),
)
self.assertEqual(ExerciseCategory.objects.count(), 6)
self.assertEqual(ExerciseCategory.objects.get(pk=1).name, 'A cooler, swaggier category')
Expand All @@ -786,6 +792,7 @@ def test_muscle_sync(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/muscle/',
headers=wger_headers(),
timeout=wger_request_timeout(),
)
self.assertEqual(Muscle.objects.count(), 7)
self.assertTrue(Muscle.objects.get(pk=2).is_front)
Expand All @@ -801,6 +808,7 @@ def test_equipment_sync(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/equipment/',
headers=wger_headers(),
timeout=wger_request_timeout(),
)
self.assertEqual(Equipment.objects.count(), 4)
self.assertEqual(Equipment.objects.get(pk=3).name, 'A big rock')
Expand All @@ -822,6 +830,7 @@ def test_deletion_log(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/deletion-log/?limit=100',
headers=wger_headers(),
timeout=wger_request_timeout(),
)
self.assertEqual(Exercise.objects.count(), 7)
self.assertEqual(Translation.objects.count(), 8)
Expand Down Expand Up @@ -863,6 +872,7 @@ def test_exercise_sync(self, mock_request):
mock_request.assert_called_with(
'https://wger.de/api/v2/exerciseinfo/?limit=100',
headers=wger_headers(),
timeout=wger_request_timeout(),
)
self.assertEqual(Exercise.objects.count(), 9)
self.assertEqual(Translation.objects.count(), 14)
Expand Down Expand Up @@ -929,7 +939,10 @@ def test_exercise_sync(self, mock_request):

@patch('requests.get', return_value=MockImageResponse())
def test_image_sync(self, mock_request):
"""Test that download_exercise_images updates existing images and creates new ones"""
"""
Test that download_exercise_images updates existing images and creates new ones,
passing a request timeout to every request
"""

# Arrange
initial_image_count = ExerciseImage.objects.count()
Expand Down Expand Up @@ -963,6 +976,9 @@ def test_image_sync(self, mock_request):
self.assertEqual(new_image.license_title, 'New Image Title')
self.assertEqual(new_image.license_author, 'New Author')

for call in mock_request.call_args_list:
self.assertEqual(call.kwargs.get('timeout'), wger_request_timeout())

@patch('requests.get', return_value=MockInvalidImageResponse())
def test_image_sync_skips_invalid_image(self, mock_request):
"""A download whose bytes are not a valid image is skipped, not stored."""
Expand Down Expand Up @@ -993,10 +1009,13 @@ def test_video_sync_skips_invalid_video(self, mock_request):

@patch('requests.get', return_value=MockValidVideoResponse())
def test_video_sync_stores_valid_video(self, mock_request):
"""A downloaded video is stored under the remote file's extension."""
"""A downloaded video is stored under the remote file's extension, fetched with timeout."""

with tempfile.TemporaryDirectory() as media_root, self.settings(MEDIA_ROOT=media_root):
download_exercise_videos(lambda x: x)

video = ExerciseVideo.objects.get(uuid='00000088-1d00-4e9d-a1a4-5f5ebd15e819')
self.assertTrue(video.video.name.endswith('.mov'))

for call in mock_request.call_args_list:
self.assertEqual(call.kwargs.get('timeout'), wger_request_timeout())
7 changes: 5 additions & 2 deletions wger/nutrition/management/commands/import-off-products.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
)
from wger.nutrition.extract_info.off import extract_info_from_off
from wger.nutrition.management.products import ImportProductCommand
from wger.utils.requests import wger_headers
from wger.utils.requests import (
wger_headers,
wger_request_timeout,
)


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -98,7 +101,7 @@ def import_daily_delta(self, languages: dict[str, int], destination: str):

# Fetch the index page with requests and read the result
index_url = self.deltas_base_url + 'index.txt'
req = requests.get(index_url, headers=wger_headers())
req = requests.get(index_url, headers=wger_headers(), timeout=wger_request_timeout())
req.raise_for_status()
index_content = req.text
newest_entry = index_content.split('\n')[0]
Expand Down
9 changes: 7 additions & 2 deletions wger/nutrition/management/products.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@
from wger.nutrition.consts import SyncMode
from wger.nutrition.dataclasses import IngredientData
from wger.nutrition.models import Ingredient
from wger.utils.requests import wger_headers
from wger.utils.requests import (
wger_headers,
wger_request_timeout,
)


logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -173,7 +176,9 @@ def download_file(self, url: str, destination: str) -> None:
return

self.stdout.write(f'Downloading {url}... (this may take a while)')
response = requests.get(url, stream=True, headers=wger_headers())
response = requests.get(
url, stream=True, headers=wger_headers(), timeout=wger_request_timeout()
)
response.raise_for_status()
total_size = int(response.headers.get('content-length', 0))

Expand Down
24 changes: 18 additions & 6 deletions wger/nutrition/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,10 @@
)
from wger.utils.language import load_language
from wger.utils.requests import (
WgerTimeoutSession,
get_paginated,
wger_headers,
wger_request_timeout,
wger_user_agent,
)
from wger.utils.url import make_uri
Expand Down Expand Up @@ -181,7 +183,7 @@ def fetch_ingredient_image(pk: int):
def fetch_image_from_wger_instance(ingredient):
url = make_uri(IMAGE_ENDPOINT, query={'ingredient__uuid': ingredient.uuid})
logger.info(f'Trying to fetch image from WGER for {ingredient.name} (UUID: {ingredient.uuid})')
result = requests.get(url, headers=wger_headers()).json()
result = requests.get(url, headers=wger_headers(), timeout=wger_request_timeout()).json()
if result['count'] == 0:
logger.info('No image for ingredient found in the remote server')
return
Expand All @@ -193,7 +195,9 @@ def fetch_image_from_wger_instance(ingredient):
logger.info('image already present locally, skipping...')
return
except Image.DoesNotExist:
retrieved_image = requests.get(image_data['image'], headers=wger_headers())
retrieved_image = requests.get(
image_data['image'], headers=wger_headers(), timeout=wger_request_timeout()
)
try:
image = Image.from_json(ingredient, retrieved_image, image_data)
except ValidationError as e:
Expand Down Expand Up @@ -252,7 +256,9 @@ def fetch_image_from_off(ingredient: Ingredient):
logger.info('could not load all image information, skipping...', e)
return

off_response = download_image(image_url, return_struct=True)
# The OFF library sends its requests without a timeout
with WgerTimeoutSession() as session:
off_response = download_image(image_url, return_struct=True, session=session)

# Save to DB
url = make_uri(
Expand Down Expand Up @@ -312,7 +318,9 @@ def download_ingredient_images(
continue
except Image.DoesNotExist:
print_fn(' Image not found in local DB, creating now...')
retrieved_image = requests.get(image_data['image'], headers=headers)
retrieved_image = requests.get(
image_data['image'], headers=headers, timeout=wger_request_timeout()
)
try:
Image.from_json(ingredient, retrieved_image, image_data)
except ValidationError as e:
Expand Down Expand Up @@ -377,7 +385,9 @@ def sync_ingredients(
query={**filter_query, 'limit': 1},
)
try:
count_response = requests.get(count_url, headers=wger_headers(), timeout=30).json()
count_response = requests.get(
count_url, headers=wger_headers(), timeout=wger_request_timeout()
).json()
total = count_response.get('count')
except (requests.RequestException, ValueError) as e:
logger.info(f'Could not fetch total ingredient count: {e}')
Expand Down Expand Up @@ -638,7 +648,9 @@ def download_ingredient_dump(
else:
file_path = Path(tempfile.NamedTemporaryFile(delete=False, suffix='.jsonl.gz').name)

response = requests.get(dump_url, stream=True, headers=wger_headers(), timeout=(10, 60))
response = requests.get(
dump_url, stream=True, headers=wger_headers(), timeout=wger_request_timeout()
)
if response.status_code == 404:
raise FileNotFoundError(
f'Bulk ingredient dump not found at {dump_url}. '
Expand Down
7 changes: 5 additions & 2 deletions wger/nutrition/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
sync_ingredients,
sync_ingredients_from_dump,
)
from wger.utils.requests import wger_headers
from wger.utils.requests import (
wger_headers,
wger_request_timeout,
)
from wger.utils.url import make_uri


Expand Down Expand Up @@ -136,7 +139,7 @@ def sync_all_ingredients_chunked_task(
server_url=remote,
query={'ordering': '-id', 'limit': 1},
)
data = requests.get(url, headers=wger_headers(), timeout=30).json()
data = requests.get(url, headers=wger_headers(), timeout=wger_request_timeout()).json()
if data.get('count', 0) == 0:
logger.info('Remote has no ingredients, nothing to sync.')
return None
Expand Down
Loading
Loading