Merge branch 'master' into feature/health-sync

# Conflicts:
#	lib/l10n/app_de.arb
#	lib/l10n/app_es.arb
#	lib/l10n/app_fr.arb
This commit is contained in:
Roland Geider
2026-07-28 22:39:59 +02:00
96 changed files with 4672 additions and 464 deletions

View File

@@ -38,9 +38,6 @@ jobs:
- name: Common flutter setup
uses: ./.github/actions/flutter-common
- name: Install dependencies
run: flutter pub get
- name: Analyze
run: flutter analyze

View File

@@ -86,23 +86,17 @@ jobs:
uses: actions/checkout@v7
with:
repository: wger-project/de.wger.flutter
ssh-key: ${{ secrets.SSH_DEPLOY_KEY }}
- name: Bump version and update manifest
run: |
git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.14.1 ../flatpak-flutter
git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.15.0 ../flatpak-flutter
pip install -r ../flatpak-flutter/requirements.txt
python bump-versions.py ${{ inputs.ref }} ${{ needs.build_linux.outputs.flutter_sdk_version }}
../flatpak-flutter/flatpak-flutter.py --app-module wger flatpak-flutter.yml
- name: Push updated config to flathub repository
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}
run: |
mkdir -p ~/.ssh
echo "$SSH_DEPLOY_KEY" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config user.name "github-actions"
git config user.email "github-actions@github.com"
git checkout -b release-${{ inputs.ref }}

View File

@@ -20,10 +20,18 @@ on:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
name: Run tests
name: Run tests (shard ${{ matrix.shard }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
shard: [0, 1, 2, 3]
env:
TZ: Europe/Berlin
steps:
@@ -32,19 +40,31 @@ jobs:
- name: Common flutter setup
uses: ./.github/actions/flutter-common
- name: Install dependencies
run: |
sudo apt install libsqlite3-dev lcov --no-install-recommends
flutter pub get
- name: Install system dependencies
run: sudo apt install libsqlite3-dev lcov --no-install-recommends
# Removing some folders from the coverage since these files are not really
# part of the app code and just get in the way of the report
- name: Test app
run: |
flutter test --coverage
flutter test --coverage --total-shards 4 --shard-index ${{ matrix.shard }}
lcov --remove coverage/lcov.info 'lib/l10n/generated/*' 'lib/theme/*' -o coverage/lcov.info
- name: Coveralls
- name: Upload coverage to Coveralls
uses: coverallsapp/github-action@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
flag-name: shard-${{ matrix.shard }}
parallel: true
finish:
name: Finish coverage
needs: test
runs-on: ubuntu-latest
if: ${{ always() }}
steps:
- name: Close parallel Coveralls build
uses: coverallsapp/github-action@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
parallel-finished: true

View File

@@ -8,8 +8,8 @@ GEM
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1260.0)
aws-sdk-core (3.252.0)
aws-partitions (1.1272.0)
aws-sdk-core (3.254.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
@@ -17,11 +17,11 @@ GEM
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.129.0)
aws-sdk-core (~> 3, >= 3.248.0)
aws-sdk-kms (1.130.0)
aws-sdk-core (~> 3, >= 3.254.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.225.1)
aws-sdk-core (~> 3, >= 3.248.0)
aws-sdk-s3 (1.228.0)
aws-sdk-core (~> 3, >= 3.254.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
@@ -42,8 +42,9 @@ GEM
domain_name (0.6.20240107)
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.112.0)
faraday (1.10.5)
excon (1.6.0)
logger
faraday (1.10.6)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
@@ -72,10 +73,10 @@ GEM
faraday_middleware (1.2.1)
faraday (~> 1.0)
fastimage (2.4.1)
fastlane (2.236.1)
fastlane (2.237.0)
CFPropertyList (>= 2.3, < 5.0.0)
abbrev (~> 0.1)
addressable (>= 2.8, < 3.0.0)
addressable (>= 2.9.0, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.197)
babosa (>= 1.0.3, < 2.0.0)
@@ -87,7 +88,7 @@ GEM
csv (~> 3.3)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
excon (>= 0.71.0, < 2.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
@@ -126,7 +127,7 @@ GEM
fastlane-plugin-versioning (0.7.1)
fastlane-sirp (1.1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.102.0)
google-apis-androidpublisher_v3 (0.105.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
addressable (~> 2.5, >= 2.5.1)
@@ -136,11 +137,11 @@ GEM
mutex_m
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
google-apis-iamcredentials_v1 (0.27.0)
google-apis-iamcredentials_v1 (0.28.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-playcustomapp_v1 (0.17.0)
google-apis-playcustomapp_v1 (0.18.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-storage_v1 (0.63.0)
google-apis-storage_v1 (0.65.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.9.0)
google-cloud-env (>= 1.0, < 3.a)
@@ -148,8 +149,8 @@ GEM
google-cloud-env (2.2.2)
base64 (~> 0.2)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.6.0)
google-cloud-storage (1.61.0)
google-cloud-errors (1.7.0)
google-cloud-storage (1.62.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-core (>= 0.18, < 2)
@@ -159,7 +160,7 @@ GEM
googleauth (~> 1.9)
mini_mime (~> 1.0)
google-logging-utils (0.2.0)
googleauth (1.17.0)
googleauth (1.17.1)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.2)
google-logging-utils (~> 0.1)
@@ -173,7 +174,7 @@ GEM
httpclient (2.9.0)
mutex_m
jmespath (1.6.2)
json (2.19.9)
json (2.21.1)
jwt (3.2.0)
base64
logger (1.7.0)
@@ -220,12 +221,14 @@ GEM
uber (0.1.0)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
xcodeproj (1.27.0)
xcodeproj (1.28.1)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
base64
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
nkf
rexml (>= 3.3.6, < 4.0)
xcpretty (0.4.1)
rouge (~> 3.28.0)

View File

@@ -53,7 +53,7 @@ flutter run
This is a regular flutter application, so there's no magic. You will need a backend
for this, so feel free to use the test server for this (the db is reset daily):
* URL: `https://wger-master.rge.uber.space`
* URL: `https://dev.wger.de`
* username: `user`
* password: `flutteruser`

View File

@@ -2,7 +2,7 @@
هل وجدت تطبيقك الرياضي المفضل، وتستمتع بابتكار برامجك التدريبية الخاصة؟ مهما كان شغفك بالرياضة – يجمعنا قاسم مشترك: وهو شغفنا بمتابعة بياناتنا الصحية <3
لا تقلق إن كنت لا تزال تدير رحلتك الرياضية بدفتر ملاحظاتك التقليدي، ولكن ندعوك للانضمام إلى مستقبل اللياقة في 2025!
لا تقلق إن كنت لا تزال تدير رحلتك الرياضية بدفتر ملاحظاتك التقليدي، ولكن ندعوك للانضمام إلى مستقبل اللياقة في 2026!
طورنا لك تطبيقًا رقميًا مجانيًا 100% لمتابعة صحتك ولياقتك، يركز على أهم الميزات الأساسية لتسهيل حياتك. ابدأ الآن، واصل تدريبك، واحتفل بكل إنجاز تحققه!

View File

@@ -2,7 +2,7 @@ From fitness lovers to fitness lovers – get your health organized with WGER, y
Have you already found your #1 fitness app and do you love to create your own sports routines? No matter what type of sporty beast you are – we all have something in common: We love to keep track of our health data <3
So we don’t judge you for still managing your fitness journey with your handy little workout log book but welcome to 2025!
So we don’t judge you for still managing your fitness journey with your handy little workout log book but welcome to 2026!
We have developed a 100% free digital health and fitness tracker app for you, sized down to the most relevant features to make your life easier. Get started, keep training and celebrate your progress!

View File

@@ -2,7 +2,7 @@ Von Fitnessliebhabern für Fitnessliebhaber, organisiere deine Gesundheit mit wg
Hast du schon deine Nr. 1 Fitness-Anwendung gefunden und liebst es, deine eigene Trainingspläne zu erstellen? Egal was für ein sportliches Biest du bist sind – wir haben alle etwas gemeinsam: wir lieben es, den Überblick über unsere Gesundheitsdaten zu behalten <3
Wir verurteilen dich also nicht dafür, dass du deine Fitness-Reise immer noch mit deinem kleinen Tagebuch verwaltest, aber willkommen im Jahr 2025!
Wir verurteilen dich also nicht dafür, dass du deine Fitness-Reise immer noch mit deinem kleinen Tagebuch verwaltest, aber willkommen im Jahr 2026!
Wir haben eine 100 % kostenlose digitale Gesundheits- und Fitnesstracker-Anwendung für dich entwickelt, die auf die wichtigsten Funktionen reduziert ist, um dein Leben einfacher zu machen. Lege jetzt lost, trainiere weiter und feiere deine Fortschritte!

View File

@@ -2,7 +2,7 @@
Έχετε ήδη βρει την #1 εφαρμογή γυμναστικής σας και σας αρέσει να δημιουργείτε τις δικές σας αθλητικές ρουτίνες; Ανεξάρτητα από το είδος του σπορ θηρίου που είστε – όλοι έχουμε κάτι κοινό: Μας αρέσει να παρακολουθούμε τα δεδομένα υγείας μας <3
Επομένως, δεν σας κρίνουμε επειδή εξακολουθείτε να διαχειρίζεστε το ταξίδι σας στη φυσική κατάσταση με το εύχρηστο μικρό ημερολόγιο προπόνησης, αλλά καλώς ήρθατε στο 2025!
Επομένως, δεν σας κρίνουμε επειδή εξακολουθείτε να διαχειρίζεστε το ταξίδι σας στη φυσική κατάσταση με το εύχρηστο μικρό ημερολόγιο προπόνησης, αλλά καλώς ήρθατε στο 2026!
Έχουμε αναπτύξει μια 100% δωρεάν ψηφιακή εφαρμογή παρακολούθησης υγείας και φυσικής κατάστασης για εσάς, με μέγεθος στις πιο σχετικές λειτουργίες για να διευκολύνει τη ζωή σας. Ξεκινήστε, συνεχίστε την προπόνηση και γιορτάστε την πρόοδό σας!

View File

@@ -2,7 +2,7 @@ From fitness lovers to fitness lovers – get your health organized with WGER, y
Have you already found your #1 fitness app and do you love to create your own sports routines? No matter what type of sporty beast you are – we all have something in common: We love to keep track of our health data <3
So we don’t judge you for still managing your fitness journey with your handy little workout log book but welcome to 2025!
So we don’t judge you for still managing your fitness journey with your handy little workout log book but welcome to 2026!
We have developed a 100% free digital health and fitness tracker app for you, sized down to the most relevant features to make your life easier. Get started, keep training and celebrate your progress!

View File

@@ -2,7 +2,7 @@ Entre amoureux du fitness et amoureux de la forme, organisez votre santé avec W
Vous avez déjà trouvé votre application de fitness nº 1 et vous aimez créer vos propres routines sportives ? Quel que soit le type de bête sportive que vous êtes - nous avons tous quelque chose en commun : nous aimons garder la trace de nos données de santé <3.
Nous ne vous jugeons donc pas si vous continuez à gérer votre parcours de remise en forme avec votre petit carnet d'entraînement bien pratique, mais bienvenue en 2025 !
Nous ne vous jugeons donc pas si vous continuez à gérer votre parcours de remise en forme avec votre petit carnet d'entraînement bien pratique, mais bienvenue en 2026 !
Nous avons conçu pour vous une application numérique de suivi de la santé et de la forme physique 100 % gratuite, dimensionnée aux fonctionnalités les plus pertinentes pour vous faciliter la vie. Lancez-vous, continuez à vous entraîner et célébrez vos progrès !

View File

@@ -2,7 +2,7 @@ Od ljubitelja fitnessa za ljubitelje fitnessa – organiziraj svoje zdravlje s W
Već si pronašao/la omiljeni program za fitness i voliš stvarati vlastite sportske rutine? Bez obzira na vrstu sporta kojim se baviš – svi imamo nešto zajedničko: Volimo pratiti naše zdravstvene podatke <3
Stoga te ne osuđujemo što još uvijek upravljaš svojim fitnessom sa svojim praktičnim malim dnevnikom vježbanja, ali nalazimo se u 2025. godini!
Stoga te ne osuđujemo što još uvijek upravljaš svojim fitnessom sa svojim praktičnim malim dnevnikom vježbanja, ali nalazimo se u 2026. godini!
Razvili smo 100 % besplatan program za digitalno praćenje zdravlja i fitnessa, s najrelevantnijim funkcijama koje će ti olakšati život. Započni i nastavi trenirati te slavi svoj napredak!

View File

@@ -0,0 +1,39 @@
Fitneszrajongóktól fitneszrajongóknak – rendszerezd az egészségeddel kapcsolatos adatokat a WGERrel, a saját edzéskezelőddel!
Már megtaláltad az első számú fitneszalkalmazásodat, és szereted saját magad összeállítani az edzésprogramjaidat? Nem számít, milyen sportőrült vagy – egyvalami mindannyiunkban közös: szeretjük nyomon követni az egészségügyi adatainkat <3
Nem ítélünk el azért, ha még mindig a praktikus kis edzésnaplófüzetedben vezeted a fejlődésedet, de üdv 2026-ban!
Kifejlesztettünk neked egy 100%-ban ingyenes, digitális egészség- és fitneszkövető alkalmazást, amely csak a legfontosabb funkciókat tartalmazza, hogy egyszerűbbé tegye az életedet. Kezdd el, folytasd az edzést, és ünnepeld a fejlődésedet!
A wger egy nyílt forráskódú projekt, amelynek középpontjában a következők állnak:
* A tested
* Az edzéseid
* A fejlődésed
* Az adataid
A tested:
Nem kell rákeresned kedvenc ételeid összetevőire – válaszd ki napi étkezéseidet több mint 78 000 termék közül, és tekintsd meg azok tápértékadatait. Add hozzá az étkezéseket a táplálkozási tervedhez, és kövesd nyomon étrendedet a naptárban.
Az edzéseid:
Te tudod a legjobban, mi tesz jót a testednek. Állítsd össze saját edzéseidet a több mint 200 különböző gyakorlatot tartalmazó, folyamatosan bővülő kínálatból. Ezután használd az Edzőtermi módot, amely végigvezet az edzésen, miközben egyetlen koppintással rögzítheted a használt súlyokat.
A fejlődésed:
Soha ne téveszd szem elől a céljaidat. Kövesd nyomon a testsúlyodat, és tekintsd meg a statisztikáidat.
Az adataid:
A wger a személyre szabott fitnesznaplód – az adataid azonban a te tulajdonodban maradnak. A REST API segítségével hozzáférhetsz az adataidhoz, és nagyszerű dolgokat valósíthatsz meg velük.
Kérjük, vedd figyelembe: ez az ingyenes alkalmazás nem részesül külső finanszírozásban, és adományt sem kérünk. A wger egy folyamatosan fejlődő közösségi projekt, ezért bármikor új funkciók jelenhetnek meg!
#NyíltForráskód – mit jelent ez?
A nyílt forráskód azt jelenti, hogy az alkalmazás és a hozzá kapcsolódó szerver teljes forráskódja ingyenesen és bárki számára elérhető:
* Saját szervereden szeretnéd futtatni a wgert magadnak vagy a helyi edzőtermed számára? Rajta!
* Hiányzik egy funkció, és szeretnéd megvalósítani? Kezdd el most!
* Ellenőrizni szeretnéd, hogy az alkalmazás nem küld-e adatokat illetéktelen helyre? Megteheted!
Csatlakozz közösségünkhöz, és légy része a világ minden tájáról érkező sportrajongók és informatikai megszállottak csapatának. Folyamatosan dolgozunk az alkalmazás saját igényeinkhez igazított fejlesztésén és optimalizálásán. Örömmel fogadjuk a visszajelzéseidet, ezért bármikor csatlakozhatsz, és megoszthatod velünk kívánságaidat és ötleteidet!
-> A forráskódot itt találod: https://github.com/wger-project
-> Tedd fel kérdéseidet, vagy csak köszönj be Discord-szerverünkön: https://discord.gg/rPWFv6W

View File

@@ -0,0 +1 @@
Fitnesz-, edzés-, táplálkozás- és testsúlykövető

View File

@@ -0,0 +1 @@
wger Workout Manager

View File

@@ -2,7 +2,7 @@ Da amanti del fitness per amanti del fitness – Organizza la tua salute con WGE
Hai già trovato la tua applicazione per il fitness nº 1 e ti piace creare le tue routines sportive? Non importa che tipo di sportivo sei – Abbiamo tutti qualcosa in comune: Amiamo tenere sotto controllo i dati sulla nostra salute <3
Quindi non ti giudichiamo se stai ancora tenendo traccia dei tuoi allenamenti con un vecchio quaderno, ma ora ti diamo il benvenuto nel 2025!
Quindi non ti giudichiamo se stai ancora tenendo traccia dei tuoi allenamenti con un vecchio quaderno, ma ora ti diamo il benvenuto nel 2026!
Abbiamo sviluppato una applicazione 100% gratuita, questa applicazione tiene traccia dei tuoi allenamenti per te alleggerita alle funzionalità più importanti per semplificarti la vita. Inizia, monitora, e celebra i tuoi progressi!

View File

@@ -2,7 +2,7 @@ From fitness lovers to fitness lovers – get your health organized with WGER, y
Have you already found your #1 fitness app and do you love to create your own sports routines? No matter what type of sporty beast you are – we all have something in common: We love to keep track of our health data <3
So we don’t judge you for still managing your fitness journey with your handy little workout log book but welcome to 2025!
So we don’t judge you for still managing your fitness journey with your handy little workout log book but welcome to 2026!
We have developed a 100% free digital health and fitness tracker app for you, sized down to the most relevant features to make your life easier. Get started, keep training and celebrate your progress!

View File

@@ -2,7 +2,7 @@
이미 당신만의 최고의 피트니스 앱을 찾았나요? 자신만의 운동 루틴을 만드는 걸 좋아하나요? 어떤 운동 스타일이든 우리는 공통점이 있습니다: 건강 데이터를 기록하는 걸 좋아한다는 점이죠. ❤️
아직도 작은 운동 일지에 피트니스 여정을 기록하고 있다면 괜찮아요. 하지만 이제 2025년에 오신 걸 환영합니다!
아직도 작은 운동 일지에 피트니스 여정을 기록하고 있다면 괜찮아요. 하지만 이제 2026년에 오신 걸 환영합니다!
우리는 여러분의 삶을 더 쉽게 만들어주는, 꼭 필요한 기능만 담은 100% 무료 디지털 건강 & 피트니스 트래커 앱을 개발했습니다.
지금 바로 시작하고, 꾸준히 운동하며, 성장하는 모습을 축하하세요!

View File

@@ -2,7 +2,7 @@
Веќе ја најдовте вашата апликација број 1 за фитнес и сакате да креирате свои спортски рутини? Без разлика каква спортска ѕверка сте – сите имаме нешто заедничко: Сакаме да го следиме нашето здравје <3
Затоа нема да ве осудуваме што сè уште го водите вашиот фитнес пат со вашата мала рачна тетратка за тренинзи, но добредојдовте во 2025!
Затоа нема да ве осудуваме што сè уште го водите вашиот фитнес пат со вашата мала рачна тетратка за тренинзи, но добредојдовте во 2026!
Развивме 100% бесплатна дигитална апликација за следење на здравје и фитнес, сведена на најважните функции за да ви го олесниме животот. Започнете, продолжете да тренирате и прославувајте го вашиот напредок!

View File

@@ -2,7 +2,7 @@ Fra treningsentusiaster til treningsentusiaster – få helsen din organisert me
Har du allerede funnet din favoritt treningsapp og elsker du å lage dine egne treningsrutiner? Uansett hvilken type treningsgal du er – vi har alle noe til felles: Vi elsker å holde oversikt over helsedata <3
Så vi dømmer deg ikke for at du fortsatt styrer treningsreisen din med den lille treningsdagboken din, men velkommen til 2025!
Så vi dømmer deg ikke for at du fortsatt styrer treningsreisen din med den lille treningsdagboken din, men velkommen til 2026!
Vi har utviklet en 100% gratis digital helse- og treningssporer-app for deg, trimmet ned til de mest relevante funksjonene for å gjøre livet ditt enklere. Kom i gang, fortsett å trene og feir fremgangen din!

View File

@@ -2,7 +2,7 @@ Van fitness liefhebbers, vóór fitness liefhebbers - krijg inzicht in je sport
Heb je je favoriete fitnessapp al gevonden en vind je het leuk om je eigen sportroutines te creëren? Wat voor sportbeest je ook bent, we hebben allemaal iets gemeen: we houden graag onze gezondheidsgegevens bij.
Dus we beoordelen je niet om het feit dat je je fitness reis nog met een workout logboekje bijhoudt, maar verwelkomen je graag naar 2025!
Dus we beoordelen je niet om het feit dat je je fitness reis nog met een workout logboekje bijhoudt, maar verwelkomen je graag naar 2026!
We hebben een 100% gratis digitale gezondheids- en fitnesstracker-app voor je ontwikkeld, met de meest relevante functies om je leven makkelijker te maken. Ga aan de slag, blijf trainen en vier je voortgang!

View File

@@ -2,7 +2,7 @@ Od miłośników fitnessu dla miłośników fitnessu – zorganizuj zdrowy tryb
Znalazłeś już swoją najlepszą aplikację do fitnessu i lubisz tworzyć własne programy sportowe? Bez względu na to, jakim jesteś typem wysportowanej bestii – wszyscy mamy coś wspólnego: uwielbiamy śledzić nasze dane dotyczące zdrowia <3
Więc nie oceniamy Cię za to, że nadal zarządzasz swoją podróżą przez świat fitness za pomocą poręcznego małego zeszytu treningowego, ale witaj w 2025 roku!
Więc nie oceniamy Cię za to, że nadal zarządzasz swoją podróżą przez świat fitness za pomocą poręcznego małego zeszytu treningowego, ale witaj w 2026 roku!
Opracowaliśmy dla Ciebie w 100% darmową cyfrową aplikację do monitorowania zdrowia i kondycji, dostosowaną do najistotniejszych funkcji, aby ułatwić Ci życie. Rozpocznij, kontynuuj trening i świętuj swoje postępy!

View File

@@ -2,7 +2,7 @@ De amantes de fitness a amantes de fitness - organize sua saúde com WGER, seu W
Você já encontrou seu aplicativo de fitness n.º 1 e adora criar suas próprias rotinas esportivas? Não importa que tipo de animal esportivo você seja - todos nós temos algo em comum: adoramos acompanhar nossos dados de saúde <3
Portanto, não o julgamos por você ainda gerenciar sua jornada de condicionamento físico com seu pequeno livro de registro de treino, mas bem-vindo a 2025!
Portanto, não o julgamos por você ainda gerenciar sua jornada de condicionamento físico com seu pequeno livro de registro de treino, mas bem-vindo a 2026!
Desenvolvemos um aplicativo rastreador digital de saúde e condicionamento físico 100% gratuito para você, dimensionado para os recursos mais relevantes para facilitar sua vida. Comece, continue treinando, e comemore seu progresso!

View File

@@ -2,7 +2,7 @@ De amantes do exercício para amantes do exercício - Organiza a tua saúde com
Já encontraste a tua aplicação fitness n.º 1 e adoras criar as tuas próprias rotinas desportivas? Independentemente do animal desportivo que sejas, todos temos algo em comum: adoramos dominar os nossos dados biométricos <3
Por isso não te julgamos se ainda fazes os teus registos no teu lindo caderninho de treino, mas bem-vindo a 2025!
Por isso não te julgamos se ainda fazes os teus registos no teu lindo caderninho de treino, mas bem-vindo a 2026!
Desenvolvemos uma aplicação digital de controle de treino e saúde 100% livre para ti, simplificada às funções mais importantes para simplificar a tua vida. Começa, continua a treinar e celebra os teus progressos!

View File

@@ -2,7 +2,7 @@
Вы уже нашли свое фитнес-приложение №1 и любите создавать свои собственные спортивные программы? Независимо от того, какой вы спортивный зверь - у всех нас есть нечто общее: мы любим отслеживать данные о своем здоровье <3
Поэтому мы не осуждаем вас за то, что вы все еще ведете свой фитнес-путь с помощью удобного маленького журнала тренировок, но добро пожаловать в 2025 год!
Поэтому мы не осуждаем вас за то, что вы все еще ведете свой фитнес-путь с помощью удобного маленького журнала тренировок, но добро пожаловать в 2026 год!
Мы разработали для вас на 100% свободное цифровое приложение для отслеживания состояния здоровья и фитнес-тренировок, сократив его до самых необходимых функций, чтобы облегчить вам жизнь. Начните, продолжайте тренироваться и отмечайте свой прогресс!

View File

@@ -2,7 +2,7 @@
Већ си пронашао/ла омиљени програм за фитнес и волиш да уводиш спортстку рутину? Без обзира на врсту спортске активности - сви имамо нешто заједничко: волимо да пратимо наше здравствене податке! <3
Ми те не осуђујемо што још увек управљаш са својим фитнесом својим класичним дневником, али ипак се налазимо у 2025. години!
Ми те не осуђујемо што још увек управљаш са својим фитнесом својим класичним дневником, али ипак се налазимо у 2026. години!
Развили смо 100% бесплатан програм за дигитално праћење здравља и фитнеса, са најрелевантнијим функцијама које ће ти олакшати живот. Започни тренинг и прослави своје прве кораке!

View File

@@ -2,7 +2,7 @@
நீங்கள் ஏற்கனவே உங்கள் #1 உடற்பயிற்சி செயலியைக் கண்டுபிடித்துவிட்டீர்களா, மேலும் உங்கள் சொந்த விளையாட்டு வழக்கங்களை உருவாக்க விரும்புகிறீர்களா? நீங்கள் எந்த வகையான விளையாட்டு மிருகமாக இருந்தாலும் சரி - நம் அனைவருக்கும் பொதுவான ஒன்று உள்ளது: எங்கள் உடல்நலத் தரவைக் கண்காணிக்க நாங்கள் விரும்புகிறோம் <3
எனவே, உங்கள் உடற்பயிற்சி பயணத்தை உங்கள் எளிமையான சிறிய உடற்பயிற்சி பதிவு புத்தகத்துடன் நிர்வகிப்பதற்காக நாங்கள் உங்களை மதிப்பிடவில்லை, ஆனால் 2025 க்கு வரவேற்கிறோம்!
எனவே, உங்கள் உடற்பயிற்சி பயணத்தை உங்கள் எளிமையான சிறிய உடற்பயிற்சி பதிவு புத்தகத்துடன் நிர்வகிப்பதற்காக நாங்கள் உங்களை மதிப்பிடவில்லை, ஆனால் 2026 க்கு வரவேற்கிறோம்!
உங்களுக்காக 100% இலவச டிஜிட்டல் உடல்நலம் மற்றும் உடற்பயிற்சி கண்காணிப்பு செயலியை நாங்கள் உருவாக்கியுள்ளோம், இது உங்கள் வாழ்க்கையை எளிதாக்க மிகவும் பொருத்தமான அம்சங்களுக்கு அளவிடப்பட்டுள்ளது. தொடங்குங்கள், பயிற்சியைத் தொடருங்கள் மற்றும் உங்கள் முன்னேற்றத்தைக் கொண்டாடுங்கள்!

View File

@@ -2,7 +2,7 @@ Fitness tutkunlarından fitness severlere - Egzersiz Yöneticiniz WGER ile sağl
1 numaralı fitness uygulamanızı zaten buldunuz mu ve kendi spor rutinlerinizi oluşturmayı seviyor musunuz? Ne tür bir sportif canavar olursanız olun - hepimizin ortak bir yanı var: Sağlık verilerimizi takip etmeyi seviyoruz <3
Bu nedenle, fitness yolculuğunuzu kullanışlı küçük egzersiz kayıt defterinizle hala yönettiğiniz için sizi yargılamıyoruz, ancak 2025'e hoş geldiniz!
Bu nedenle, fitness yolculuğunuzu kullanışlı küçük egzersiz kayıt defterinizle hala yönettiğiniz için sizi yargılamıyoruz, ancak 2026'e hoş geldiniz!
Sizin için hayatınızı kolaylaştırmak için en alakalı özelliklere göre boyutlandırılmış %100 ücretsiz bir dijital sağlık ve fitness takip uygulaması geliştirdik. Başlayın, antrenmana devam edin ve ilerlemenizi kutlayın!

View File

@@ -2,7 +2,7 @@
Ви вже знайшли свій фітнес-застосунок №1 і любите створювати свої власні спортивні програми? Неважливо, який ви спортивний звір - у всіх нас є щось спільне: ми любимо стежити за даними про своє здоров'я <3
Тому ми не засуджуємо вас за те, що ви все ще ведете свій фітнес-шлях за допомогою зручного маленького журналу тренувань, але ласкаво просимо у 2025 рік!
Тому ми не засуджуємо вас за те, що ви все ще ведете свій фітнес-шлях за допомогою зручного маленького журналу тренувань, але ласкаво просимо у 2026 рік!
Ми розробили для вас 100% безплатний цифровий застосунок для відстеження стану здоров'я та фітнесу, скоротивши його до найнеобхідніших функцій, щоб полегшити вам життя. Почніть, продовжуйте тренуватися і відзначайте свій спортивний поступ!

View File

@@ -2,7 +2,7 @@
你是否已经找到了排名第一的健身应用程序,并且喜欢创建自己的运动习惯? 无论你是哪种运动野兽——我们都有一个共同点:我们喜欢跟踪我们的健康数据
因此,我们不会因为你仍然使用小笔记本来管理你的健身旅程而评判你,但欢迎来到 2025 年!
因此,我们不会因为你仍然使用小笔记本来管理你的健身旅程而评判你,但欢迎来到 2026 年!
我们为你开发了 100% 免费的数字健康和健身追踪器应用程序,压缩到最相关的功能,让你的生活更轻松。开始吧,继续训练并庆祝你的进步!

View File

@@ -2,7 +2,7 @@
你是否已經找到了排名第一的健身應用程式,並且喜歡建立自己的運動習慣? 無論你是哪種運動野獸——我們都有一個共同點:我們喜歡追蹤我們的健康資料
因此,我們不會因為你仍然使用小筆記本來管理你的健身旅程而批評你,但歡迎來到 2025 年!
因此,我們不會因為你仍然使用小筆記本來管理你的健身旅程而批評你,但歡迎來到 2026 年!
我們為你開發了 100% 免費的數位健康和健身追蹤器應用程式,壓縮到最相關的功能,讓你的生活更輕鬆。開始吧,繼續訓練並慶祝你的進步!

View File

@@ -87,6 +87,12 @@
</screenshot>
</screenshots>
<releases>
<release version="2.0.2" date="2026-07-24">
<description>
<p>Bug fixes and improvements.</p>
</description>
<url>https://github.com/wger-project/flutter/releases/tag/2.0.2</url>
</release>
<release version="2.0.1" date="2026-06-21">
<description>
<p>Bug fixes and improvements.</p>

View File

@@ -1,17 +1,15 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.7)
base64
nkf
rexml
CFPropertyList (3.0.8)
abbrev (0.1.2)
addressable (2.9.0)
public_suffix (>= 2.0.2, < 8.0)
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1196.0)
aws-sdk-core (3.240.0)
aws-partitions (1.1272.0)
aws-sdk-core (3.254.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
@@ -19,31 +17,34 @@ GEM
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.118.0)
aws-sdk-core (~> 3, >= 3.239.1)
aws-sdk-kms (1.130.0)
aws-sdk-core (~> 3, >= 3.254.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.208.0)
aws-sdk-core (~> 3, >= 3.234.0)
aws-sdk-s3 (1.228.0)
aws-sdk-core (~> 3, >= 3.254.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.3.0)
bigdecimal (4.0.1)
benchmark (0.5.0)
bigdecimal (4.1.2)
claide (1.1.0)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
csv (3.3.5)
declarative (0.0.20)
digest-crc (0.6.5)
digest-crc (0.7.0)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.6.20240107)
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.112.0)
faraday (1.10.5)
excon (1.6.0)
logger
faraday (1.10.6)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
@@ -55,9 +56,9 @@ GEM
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.7)
faraday-cookie_jar (0.0.8)
faraday (>= 0.8.0)
http-cookie (~> 1.0.0)
http-cookie (>= 1.0.0)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.1)
faraday-excon (1.1.0)
@@ -68,40 +69,49 @@ GEM
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
faraday-retry (1.0.4)
faraday_middleware (1.2.1)
faraday (~> 1.0)
fastimage (2.3.1)
fastlane (2.225.0)
CFPropertyList (>= 2.3, < 4.0.0)
addressable (>= 2.8, < 3.0.0)
fastimage (2.4.1)
fastlane (2.237.0)
CFPropertyList (>= 2.3, < 5.0.0)
abbrev (~> 0.1)
addressable (>= 2.9.0, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
aws-sdk-s3 (~> 1.197)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
base64 (~> 0.2)
benchmark (>= 0.1.0)
bundler (>= 2.4.0, < 5.0.0)
colored (~> 1.2)
commander (~> 4.6)
csv (~> 3.3)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
excon (>= 0.71.0, < 2.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.0.0)
fastlane-sirp (>= 1.1.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.0.0)
google-cloud-env (>= 1.6.0, < 2.3.0)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
jwt (>= 2.10.3, < 4)
logger (>= 1.6, < 2.0)
mini_magick (>= 4.9.4, < 5.0.0)
multi_json (~> 1.12)
multipart-post (>= 2.0.0, < 3.0.0)
mutex_m (~> 0.3)
naturally (~> 2.2)
nkf (~> 0.2)
optparse (>= 0.1.1, < 1.0.0)
ostruct (>= 0.1.0)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.5)
@@ -112,87 +122,93 @@ GEM
tty-spinner (>= 0.8.0, < 1.0.0)
word_wrap (~> 1.0.0)
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.3.0)
xcpretty (~> 0.4.1)
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
fastlane-sirp (1.0.0)
sysrandom (~> 1.0)
fastlane-sirp (1.1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.54.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-core (0.11.3)
google-apis-androidpublisher_v3 (0.105.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
googleauth (~> 1.9)
httpclient (>= 2.8.3, < 3.a)
mini_mime (~> 1.0)
mutex_m
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
google-apis-iamcredentials_v1 (0.17.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-playcustomapp_v1 (0.13.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-storage_v1 (0.31.0)
google-apis-core (>= 0.11.0, < 2.a)
google-cloud-core (1.7.1)
google-apis-iamcredentials_v1 (0.28.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-playcustomapp_v1 (0.18.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-storage_v1 (0.65.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.9.0)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-errors (1.4.0)
google-cloud-storage (1.47.0)
google-cloud-env (2.2.2)
base64 (~> 0.2)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.7.0)
google-cloud-storage (1.62.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.31.0)
google-apis-core (>= 0.18, < 2)
google-apis-iamcredentials_v1 (~> 0.18)
google-apis-storage_v1 (>= 0.42)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
googleauth (~> 1.9)
mini_mime (~> 1.0)
googleauth (1.8.1)
faraday (>= 0.17.3, < 3.a)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
google-logging-utils (0.2.0)
googleauth (1.17.1)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.2)
google-logging-utils (~> 0.1)
jwt (>= 1.4, < 4.0)
os (>= 0.9, < 2.0)
pstore (~> 0.1)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.8)
domain_name (~> 0.5)
httpclient (2.8.3)
httpclient (2.9.0)
mutex_m
jmespath (1.6.2)
json (2.9.0)
jwt (2.10.3)
json (2.21.1)
jwt (3.2.0)
base64
logger (1.7.0)
mini_magick (4.13.2)
mini_mime (1.1.5)
multi_json (1.15.0)
multi_json (1.21.1)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
naturally (2.2.1)
nkf (0.2.0)
optparse (0.6.0)
naturally (2.3.0)
nkf (0.3.0)
optparse (0.8.1)
os (1.1.4)
plist (3.7.1)
ostruct (0.6.3)
plist (3.7.2)
pstore (0.2.1)
public_suffix (7.0.5)
rake (13.2.1)
rake (13.4.2)
representable (3.2.0)
declarative (< 0.1.0)
trailblazer-option (>= 0.1.1, < 0.2.0)
uber (< 0.2.0)
retriable (3.1.2)
rexml (3.4.2)
rouge (2.0.7)
retriable (3.8.0)
rexml (3.4.4)
rouge (3.28.0)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
rubyzip (2.4.1)
security (0.1.5)
signet (0.19.0)
signet (0.22.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 3.0)
multi_json (~> 1.10)
jwt (>= 1.5, < 4.0)
simctl (1.6.10)
CFPropertyList
naturally
sysrandom (1.0.5)
terminal-notifier (2.0.0)
terminal-table (3.0.2)
unicode-display_width (>= 1.1.1, < 3)
@@ -204,15 +220,17 @@ GEM
uber (0.1.0)
unicode-display_width (2.6.0)
word_wrap (1.0.0)
xcodeproj (1.27.0)
xcodeproj (1.28.1)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
base64
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.4.0)
nkf
rexml (>= 3.3.6, < 4.0)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty (0.4.1)
rouge (~> 3.28.0)
xcpretty-travis-formatter (1.0.1)
xcpretty (~> 0.2, >= 0.0.7)
@@ -224,4 +242,4 @@ DEPENDENCIES
fastlane
BUNDLED WITH
2.5.18
4.0.11

View File

@@ -20,6 +20,8 @@ import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod/misc.dart' show ProviderListenable;
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
/// Awaits the first value of `provider` by explicitly subscribing via
/// [Ref.listen]. Use this in notifier methods (outside of `build()`)
@@ -102,6 +104,64 @@ Uri makeHeadlessUri(String serverUrl, String path) {
);
}
final _probeLogger = Logger('powersync-probe');
/// Builds `<serverUrl>/ps/`, the default path under which wger's reverse
/// proxy exposes the PowerSync service.
String _defaultPowerSyncUrl(String serverUrl) {
final server = Uri.parse(serverUrl);
final basePath = server.path.endsWith('/')
? server.path.substring(0, server.path.length - 1)
: server.path;
return Uri(
scheme: server.scheme,
host: server.host,
port: server.port,
path: '$basePath/ps/',
).toString();
}
/// Returns the first PowerSync endpoint that answers its liveness probe with
/// a 200, or null when none does.
///
/// The `powersync_url` [provided] by the server's token endpoint is tried
/// first, then `<serverUrl>/ps/` as a fallback. Probing instead of trusting
/// [provided] rescues servers whose `SITE_URL` doesn't match the URL the app
/// reaches them under (e.g. left at its `http://localhost` default): that
/// value is unreachable from the device, while the reverse proxy usually
/// still exposes the service under the default path.
Future<String?> findLivePowerSyncUrl({
required http.Client client,
required String serverUrl,
required String? provided,
Duration probeTimeout = const Duration(seconds: 5),
}) async {
final parsed = provided == null ? null : Uri.tryParse(provided);
final candidates = {
if (parsed != null && parsed.hasScheme && parsed.host.isNotEmpty) provided!,
_defaultPowerSyncUrl(serverUrl),
};
for (final candidate in candidates) {
final probeUri = Uri.parse(
'$candidate${candidate.endsWith('/') ? '' : '/'}probes/liveness',
);
// Log failed probes
try {
final response = await client.get(probeUri).timeout(probeTimeout);
if (response.statusCode == 200) {
return candidate;
}
_probeLogger.info('PowerSync probe: $probeUri returned ${response.statusCode}');
} on Exception catch (e) {
// Unreachable or timed out: try the next candidate.
_probeLogger.info('PowerSync probe: $probeUri failed: $e');
}
}
return null;
}
/// Builds the absolute URL for a server-side media file given its
/// [relativePath] (the raw value of a Django `ImageField` / `FileField`
/// as stored in the DB, e.g. `ingredients/42/foo.jpg`).

View File

@@ -53,3 +53,20 @@ DateTime? jwtExp(Map<String, dynamic>? payload) {
}
return DateTime.fromMillisecondsSinceEpoch(exp.toInt() * 1000, isUtc: true);
}
/// Projects the token lifetime (`exp - iat`) onto the local clock.
///
/// The absolute `exp` claim is server time; comparing it against the device
/// clock (as consumers of an expiry timestamp do) breaks expiry scheduling
/// when that clock is off. Taking only the lifetime from the server keeps
/// the schedule correct regardless of clock skew.
///
/// Falls back to the absolute `exp` when `iat` is missing or not numeric.
DateTime? jwtExpOnLocalClock(Map<String, dynamic>? payload) {
final iat = payload?['iat'];
final exp = payload?['exp'];
if (iat is! num || exp is! num) {
return jwtExp(payload);
}
return DateTime.now().toUtc().add(Duration(seconds: (exp - iat).toInt()));
}

View File

@@ -20,7 +20,7 @@ import 'dart:async';
import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -91,6 +91,7 @@ class NetworkStatus extends _$NetworkStatus {
StreamSubscription<List<ConnectivityResult>>? _sub;
Timer? _probeTimer;
AppLifecycleListener? _lifecycleListener;
@override
bool build() {
@@ -102,12 +103,16 @@ class NetworkStatus extends _$NetworkStatus {
}
void _init() {
check();
check(optimistic: true);
_sub = Connectivity().onConnectivityChanged.listen((conn) async {
state = await _hasConnectionAndInternet(conn);
await _update(conn, optimistic: true);
});
// A stale offline state from the background shouldn't stick until the
// next timer tick, so re-check optimistically on resume.
_lifecycleListener = AppLifecycleListener(onResume: () => check(optimistic: true));
// Connectivity events only fire on adapter changes, so an active re-probe
// is needed to notice a backend that goes down (or comes back) while the
// network stays up.
@@ -119,30 +124,47 @@ class NetworkStatus extends _$NetworkStatus {
ref.onDispose(() {
_sub?.cancel();
_probeTimer?.cancel();
_lifecycleListener?.dispose();
});
}
Future<bool> check({Duration timeout = const Duration(seconds: 1)}) async {
/// Re-checks connectivity and backend reachability, updates the state and
/// returns it.
///
/// With [optimistic] the state flips to online as soon as a network adapter
/// is available and a failed probe only downgrades it afterwards; without it
/// the state changes only once the probe has answered. The periodic re-probe
/// stays pessimistic so a dead backend doesn't flash "online" every tick.
Future<bool> check({
Duration timeout = const Duration(seconds: 1),
bool optimistic = false,
}) async {
final conn = await Connectivity().checkConnectivity();
final ok = await _hasConnectionAndInternet(conn, timeout: timeout);
state = ok;
return ok;
return _update(conn, timeout: timeout, optimistic: optimistic);
}
Future<bool> _hasConnectionAndInternet(
Future<bool> _update(
List<ConnectivityResult> conn, {
Duration timeout = const Duration(seconds: 1),
bool optimistic = false,
}) async {
// Only short-circuit when there's clearly no network adapter at all. Any
// other connectivity type (wifi, ethernet, mobile, vpn, other, ...) still
// has to prove real reachability via the probe below. An empty list
// counts as "no connection" too.
if (conn.every((c) => c == ConnectivityResult.none)) {
state = false;
return false;
}
if (optimistic) {
state = true;
}
final base = ref.read(wgerBaseProvider);
final probeUri = base.serverUrl != null ? base.makeUrl('version') : null;
return reachabilityCheck(probeUri, base.getAppNameHeaderValue(), timeout);
final ok = await reachabilityCheck(probeUri, base.getAppNameHeaderValue(), timeout);
state = ok;
return ok;
}
}

View File

@@ -164,22 +164,27 @@ class ServerGating {
return false;
}
final body = json.decode(tokenResponse.body) as Map<String, dynamic>;
final powerSyncUrl = body['powersync_url'] as String?;
if (powerSyncUrl == null || powerSyncUrl.isEmpty) {
_logger.warning('PowerSync probe: empty powersync_url in token response');
final providedUrl = body['powersync_url'] as String?;
final powerSyncUrl = await findLivePowerSyncUrl(
client: _client,
serverUrl: serverUrl,
provided: providedUrl,
);
if (powerSyncUrl == null) {
_logger.warning(
'PowerSync probe: no endpoint answered the liveness probe '
'(server-provided powersync_url: "$providedUrl")',
);
return false;
}
final probeUri = Uri.parse(
'$powerSyncUrl${powerSyncUrl.endsWith('/') ? '' : '/'}probes/liveness',
);
final probeResponse = await _client.get(probeUri);
if (probeResponse.statusCode == 200) {
await _storage.markEverSynced();
return true;
if (powerSyncUrl != providedUrl) {
_logger.warning(
'PowerSync probe: server-provided powersync_url "$providedUrl" is '
'unreachable, using $powerSyncUrl instead',
);
}
_logger.warning('PowerSync probe: liveness returned ${probeResponse.statusCode}');
return false;
await _storage.markEverSynced();
return true;
} on Exception catch (e, s) {
_logger.warning('PowerSync probe failed: $e', e, s);
return false;

View File

@@ -24,7 +24,7 @@ import 'package:wger/core/network/network_provider.dart';
import 'package:wger/core/settings_dashboard_widgets_screen.dart';
import 'package:wger/core/widgets/about.dart';
import 'package:wger/core/widgets/sync_status_dialog.dart';
import 'package:wger/database/powersync/powersync.dart' show syncStatus;
import 'package:wger/database/powersync/powersync.dart' show syncStatus, syncWatchdogProvider;
import 'package:wger/features/account/providers/account_notifier.dart';
import 'package:wger/features/account/widgets/forms.dart';
import 'package:wger/features/account/widgets/settings.dart';
@@ -53,7 +53,11 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget {
icon: Icon(status.icon),
onPressed: () => showDialog<void>(
context: context,
builder: (_) => SyncStatusDialog(syncState),
// Like syncState, the stalled flag is a snapshot taken when the dialog opens
builder: (_) => SyncStatusDialog(
syncState,
stalled: ref.read(syncWatchdogProvider).stalled.value,
),
),
),
IconButton(

View File

@@ -20,6 +20,7 @@ import 'package:flutter/material.dart';
import 'package:powersync/powersync.dart'
show CredentialsException, PowerSyncProtocolException, SyncResponseException, SyncStatus;
import 'package:wger/core/formatting/formatting.dart';
import 'package:wger/core/widgets/log_overview.dart' show LogOverviewPage;
import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/powersync/connector.dart' show RetryableUploadException;
@@ -94,7 +95,12 @@ String? _categoriseSyncError(Object error) {
class SyncStatusDialog extends StatelessWidget {
final SyncStatus _status;
const SyncStatusDialog(this._status, {super.key});
/// True when the sync stream keeps reconnecting without ever receiving
/// data (see SyncStreamWatchdog). There is no error to show in that
/// case, so the dialog adds a hint about likely network-side blockers.
final bool stalled;
const SyncStatusDialog(this._status, {this.stalled = false, super.key});
@override
Widget build(BuildContext context) {
@@ -133,6 +139,15 @@ class SyncStatusDialog extends StatelessWidget {
),
],
),
if (stalled && _status.anyError == null) ...[
const SizedBox(height: 8),
Text(
i18n.syncStatusStalledHint,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
const SizedBox(height: 16),
// Last sync timestamp if available
@@ -172,6 +187,17 @@ class SyncStatusDialog extends StatelessWidget {
],
),
actions: [
// The stalled hint and the WARNING land in the application logs;
// give the user a direct path to them.
if (stalled && _status.anyError == null)
TextButton(
onPressed: () {
final navigator = Navigator.of(context);
navigator.pop();
navigator.pushNamed(LogOverviewPage.routeName);
},
child: Text(i18n.applicationLogs),
),
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(MaterialLocalizations.of(context).closeButtonLabel),

View File

@@ -5865,9 +5865,9 @@ class $WorkoutLogTableTable extends WorkoutLogTable with TableInfo<$WorkoutLogTa
late final GeneratedColumn<int> routineId = GeneratedColumn<int>(
'routine_id',
aliasedName,
false,
true,
type: DriftSqlType.int,
requiredDuringInsert: true,
requiredDuringInsert: false,
);
static const VerificationMeta _sessionIdMeta = const VerificationMeta(
'sessionId',
@@ -6040,8 +6040,6 @@ class $WorkoutLogTableTable extends WorkoutLogTable with TableInfo<$WorkoutLogTa
_routineIdMeta,
routineId.isAcceptableOrUnknown(data['routine_id']!, _routineIdMeta),
);
} else if (isInserting) {
context.missing(_routineIdMeta);
}
if (data.containsKey('session_id')) {
context.handle(
@@ -6155,7 +6153,7 @@ class $WorkoutLogTableTable extends WorkoutLogTable with TableInfo<$WorkoutLogTa
routineId: attachedDatabase.typeMapping.read(
DriftSqlType.int,
data['${effectivePrefix}routine_id'],
)!,
),
sessionId: attachedDatabase.typeMapping.read(
DriftSqlType.string,
data['${effectivePrefix}session_id'],
@@ -6212,7 +6210,7 @@ class $WorkoutLogTableTable extends WorkoutLogTable with TableInfo<$WorkoutLogTa
class WorkoutLogTableCompanion extends UpdateCompanion<Log> {
final Value<String> id;
final Value<int> exerciseId;
final Value<int> routineId;
final Value<int?> routineId;
final Value<String?> sessionId;
final Value<int?> iteration;
final Value<int?> slotEntryId;
@@ -6247,7 +6245,7 @@ class WorkoutLogTableCompanion extends UpdateCompanion<Log> {
WorkoutLogTableCompanion.insert({
this.id = const Value.absent(),
required int exerciseId,
required int routineId,
this.routineId = const Value.absent(),
this.sessionId = const Value.absent(),
this.iteration = const Value.absent(),
this.slotEntryId = const Value.absent(),
@@ -6262,7 +6260,6 @@ class WorkoutLogTableCompanion extends UpdateCompanion<Log> {
required DateTime date,
this.rowid = const Value.absent(),
}) : exerciseId = Value(exerciseId),
routineId = Value(routineId),
date = Value(date);
static Insertable<Log> custom({
Expression<String>? id,
@@ -6305,7 +6302,7 @@ class WorkoutLogTableCompanion extends UpdateCompanion<Log> {
WorkoutLogTableCompanion copyWith({
Value<String>? id,
Value<int>? exerciseId,
Value<int>? routineId,
Value<int?>? routineId,
Value<String?>? sessionId,
Value<int?>? iteration,
Value<int?>? slotEntryId,
@@ -17645,7 +17642,7 @@ typedef $$WorkoutLogTableTableCreateCompanionBuilder =
WorkoutLogTableCompanion Function({
Value<String> id,
required int exerciseId,
required int routineId,
Value<int?> routineId,
Value<String?> sessionId,
Value<int?> iteration,
Value<int?> slotEntryId,
@@ -17664,7 +17661,7 @@ typedef $$WorkoutLogTableTableUpdateCompanionBuilder =
WorkoutLogTableCompanion Function({
Value<String> id,
Value<int> exerciseId,
Value<int> routineId,
Value<int?> routineId,
Value<String?> sessionId,
Value<int?> iteration,
Value<int?> slotEntryId,
@@ -17954,7 +17951,7 @@ class $$WorkoutLogTableTableTableManager
({
Value<String> id = const Value.absent(),
Value<int> exerciseId = const Value.absent(),
Value<int> routineId = const Value.absent(),
Value<int?> routineId = const Value.absent(),
Value<String?> sessionId = const Value.absent(),
Value<int?> iteration = const Value.absent(),
Value<int?> slotEntryId = const Value.absent(),
@@ -17990,7 +17987,7 @@ class $$WorkoutLogTableTableTableManager
({
Value<String> id = const Value.absent(),
required int exerciseId,
required int routineId,
Value<int?> routineId = const Value.absent(),
Value<String?> sessionId = const Value.absent(),
Value<int?> iteration = const Value.absent(),
Value<int?> slotEntryId = const Value.absent(),

View File

@@ -33,6 +33,7 @@ import 'package:wger/core/network/wger_base.dart';
import 'package:wger/powersync/api_client.dart';
import 'package:wger/powersync/connector.dart';
import 'package:wger/powersync/schema.dart';
import 'package:wger/powersync/sync_watchdog.dart';
part 'powersync.g.dart';
@@ -50,6 +51,16 @@ PowerSyncDatabase? _builtInstance;
/// those paths need.
PowerSyncDatabase? get builtPowerSyncInstance => _builtInstance;
/// Watches the sync status for a stream that keeps reconnecting without ever
/// delivering data (e.g. blocked by a VPN or firewall) and flags it, see
/// [SyncStreamWatchdog]. Fed from the DB's status stream by
/// [powerSyncInstanceProvider].
final syncWatchdogProvider = Provider<SyncStreamWatchdog>((ref) {
final watchdog = SyncStreamWatchdog();
ref.onDispose(watchdog.dispose);
return watchdog;
});
@Riverpod(keepAlive: true)
Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
final db = PowerSyncDatabase(
@@ -62,6 +73,8 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
_builtInstance = db;
final client = ref.read(authenticatedHttpClientProvider);
final watchdog = ref.read(syncWatchdogProvider);
final statusSubscription = db.statusStream.listen(watchdog.onStatus);
// Connect to the sync service only while the device is online. PowerSync's
// own retry loop would otherwise log a credential error on every iteration
@@ -74,6 +87,8 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
}
} else {
db.disconnect();
// Deliberate disconnect: an offline device is not a blocked stream.
watchdog.reset();
}
}
@@ -82,6 +97,8 @@ Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
ref.onDispose(() {
_builtInstance = null;
statusSubscription.cancel();
watchdog.reset();
db.close();
});
@@ -170,6 +187,7 @@ void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client)
connector: DjangoConnector(
baseUrl: baseUrl,
apiClient: ApiClient(baseUrl, client: client),
client: client,
),
);
}
@@ -182,7 +200,7 @@ final _syncStatusInternal = StreamProvider<SyncStatus?>((ref) {
final syncStatus = Provider((ref) {
// ignore: invalid_use_of_internal_member
return ref.watch(_syncStatusInternal).value ?? const SyncStatus();
return ref.watch(_syncStatusInternal).value ?? const SyncStatus.uninitialized();
});
Future<String> _getDatabasePath() async {

View File

@@ -65,7 +65,7 @@ class WorkoutLogTable extends Table {
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
IntColumn get exerciseId => integer().named('exercise_id')();
IntColumn get routineId => integer().named('routine_id')();
IntColumn get routineId => integer().named('routine_id').nullable()();
TextColumn get sessionId => text().named('session_id').nullable()();
IntColumn get iteration => integer().nullable()();
IntColumn get slotEntryId => integer().named('slot_entry_id').nullable()();

View File

@@ -53,6 +53,7 @@ class AuthScreen extends StatelessWidget {
const Image(
image: AssetImage('assets/images/logo-white.png'),
width: 85,
height: 85,
),
Container(
margin: const EdgeInsets.only(bottom: 20.0),

View File

@@ -43,9 +43,27 @@ class Log {
String? id;
late int exerciseId;
late Exercise exerciseObj;
late int routineId;
Exercise? _exerciseObj;
/// The exercise this log belongs to, throws if it was never hydrated
///
/// Logs read from the database only carry [exerciseId], joining the whole
/// exercise with its translations, images and muscles would be wasteful for
/// a value most callers don't need. Use [exerciseObjOrNull] for those.
Exercise get exerciseObj {
if (_exerciseObj == null) {
throw StateError('Log $id has no hydrated exercise (exercise ID $exerciseId)');
}
return _exerciseObj!;
}
set exerciseObj(Exercise value) => _exerciseObj = value;
/// Like [exerciseObj] but returns null instead of throwing
Exercise? get exerciseObjOrNull => _exerciseObj;
int? routineId;
String? sessionId;
int? iteration;
int? slotEntryId;
@@ -69,7 +87,7 @@ class Log {
required this.exerciseId,
this.iteration,
this.slotEntryId,
required this.routineId,
this.routineId,
this.sessionId,
this.repetitions,
this.repetitionsTarget,
@@ -84,7 +102,7 @@ class Log {
DateTime? date,
}) : date = date ?? DateTime.now();
Log.fromSetConfigData(SetConfigData setConfig, {int? routineId, this.iteration}) {
Log.fromSetConfigData(SetConfigData setConfig, {this.routineId, this.iteration}) {
date = DateTime.now();
sessionId = null;
@@ -103,10 +121,6 @@ class Log {
rir = setConfig.rir;
rirTarget = setConfig.rir;
if (routineId != null) {
this.routineId = routineId;
}
}
Log copyWith({
@@ -157,7 +171,11 @@ class Log {
out.weightUnitObj = weightUnitObj;
out.weightUnitId = weightUnitObj.id;
}
out.exerciseObj = exerciseObj;
// Logs read from the database have no exercise, so only copy an existing one
if (_exerciseObj != null) {
out.exerciseObj = _exerciseObj!;
}
return out;
}

View File

@@ -19,6 +19,7 @@
import 'package:clock/clock.dart';
import 'package:logging/logging.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:wger/features/exercises/models/exercise.dart';
import 'package:wger/features/routines/models/log.dart';
import 'package:wger/features/routines/models/repetition_unit.dart';
import 'package:wger/features/routines/models/weight_unit.dart';
@@ -35,12 +36,19 @@ class GymLogNotifier extends _$GymLogNotifier {
return null;
}
void setLog(Log log) {
/// Pass [exercise] to hydrate the copy, logs read from the database only
/// carry their exercise ID
void setLog(Log log, {Exercise? exercise}) {
// Clear the id so Drift mints a fresh UUID on insert, and the sessionId so
// the copy lands in today's session instead of the template's historical one.
state = log.copyWith(date: clock.now())
final out = log.copyWith(date: clock.now())
..id = null
..sessionId = null;
if (exercise != null) {
out.exercise = exercise;
}
state = out;
}
void setWeight(num weight) {

View File

@@ -31,6 +31,9 @@ const PREFS_SHOW_TIMER = 'showTimerPrefs';
const PREFS_ALERT_COUNTDOWN = 'alertCountdownPrefs';
const PREFS_USE_COUNTDOWN_BETWEEN_SETS = 'useCountdownBetweenSetsPrefs';
const PREFS_COUNTDOWN_DURATION = 'countdownDurationSecondsPrefs';
const PREFS_LOG_SCOPE_WEEKS = 'logScopeWeeksPrefs';
const PREFS_SHOW_DISTINCT_LOGS = 'showDistinctLogsPrefs';
const PREFS_SHOW_WORKOUT_DURATION = 'showWorkoutDurationPrefs';
/// In seconds
const DEFAULT_COUNTDOWN_DURATION = 180;
@@ -168,7 +171,9 @@ class GymModeState {
final List<PageEntry> pages;
final int currentPage;
final TimeOfDay startTime;
/// Moment the workout was started, with full seconds precision. Set when
/// gym mode is opened and reset when the user taps "start".
final DateTime workoutStart;
final DateTime validUntil;
// User settings
@@ -177,6 +182,9 @@ class GymModeState {
final bool alertOnCountdownEnd;
final bool useCountdownBetweenSets;
final Duration countdownDuration;
final int? logScopeWeeks;
final bool showDistinctLogs;
final bool showWorkoutDuration;
// Routine data
late final int dayId;
@@ -193,15 +201,17 @@ class GymModeState {
this.alertOnCountdownEnd = true,
this.useCountdownBetweenSets = false,
this.countdownDuration = const Duration(seconds: DEFAULT_COUNTDOWN_DURATION),
this.logScopeWeeks,
this.showDistinctLogs = true,
this.showWorkoutDuration = true,
int? dayId,
int? iteration,
Routine? routine,
DateTime? validUntil,
TimeOfDay? startTime,
DateTime? workoutStart,
}) : validUntil = validUntil ?? clock.now().add(DEFAULT_DURATION),
startTime = startTime ?? TimeOfDay.fromDateTime(clock.now()) {
workoutStart = workoutStart ?? clock.now() {
if (dayId != null) {
this.dayId = dayId;
}
@@ -225,7 +235,7 @@ class GymModeState {
int? dayId,
int? iteration,
DateTime? validUntil,
TimeOfDay? startTime,
DateTime? workoutStart,
Routine? routine,
// User settings
@@ -234,6 +244,10 @@ class GymModeState {
bool? alertOnCountdownEnd,
bool? useCountdownBetweenSets,
int? countdownDuration,
int? logScopeWeeks,
bool clearLogScopeWeeks = false,
bool? showDistinctLogs,
bool? showWorkoutDuration,
}) {
return GymModeState(
isInitialized: isInitialized ?? this.isInitialized,
@@ -243,7 +257,7 @@ class GymModeState {
dayId: dayId ?? this.dayId,
iteration: iteration ?? this.iteration,
validUntil: validUntil ?? this.validUntil,
startTime: startTime ?? this.startTime,
workoutStart: workoutStart ?? this.workoutStart,
routine: routine ?? this.routine,
showExercisePages: showExercisePages ?? this.showExercisePages,
@@ -253,9 +267,15 @@ class GymModeState {
countdownDuration: Duration(
seconds: countdownDuration ?? this.countdownDuration.inSeconds,
),
logScopeWeeks: clearLogScopeWeeks ? null : (logScopeWeeks ?? this.logScopeWeeks),
showDistinctLogs: showDistinctLogs ?? this.showDistinctLogs,
showWorkoutDuration: showWorkoutDuration ?? this.showWorkoutDuration,
);
}
/// The start of the workout as a [TimeOfDay], e.g. for the session form
TimeOfDay get startTime => TimeOfDay.fromDateTime(workoutStart);
int get totalPages {
// Main pages (start, session, etc.)
var count = pages.where((p) => p.type != PageType.set).length;
@@ -320,7 +340,7 @@ class GymModeState {
return 'GymState('
'currentPage: $currentPage, '
'validUntil: $validUntil '
'startTime: $startTime, '
'workoutStart: $workoutStart, '
'showExercisePages: $showExercisePages, '
'showTimerPages: $showTimerPages, '
')';

View File

@@ -72,13 +72,31 @@ class GymStateNotifier extends _$GymStateNotifier {
);
}
final logScopeWeeks = await prefs.getInt(PREFS_LOG_SCOPE_WEEKS);
if (logScopeWeeks != null && logScopeWeeks != state.logScopeWeeks) {
state = state.copyWith(logScopeWeeks: logScopeWeeks);
}
final showDistinctLogs = await prefs.getBool(PREFS_SHOW_DISTINCT_LOGS);
if (showDistinctLogs != null && showDistinctLogs != state.showDistinctLogs) {
state = state.copyWith(showDistinctLogs: showDistinctLogs);
}
final showWorkoutDuration = await prefs.getBool(PREFS_SHOW_WORKOUT_DURATION);
if (showWorkoutDuration != null && showWorkoutDuration != state.showWorkoutDuration) {
state = state.copyWith(showWorkoutDuration: showWorkoutDuration);
}
_logger.finer(
'Loaded saved preferences: '
'showExercise=$showExercise '
'showTimer=$showTimer '
'alertOnCountdownEnd=$alertOnCountdownEnd '
'useCountdownBetweenSets=$useCountdownBetweenSets '
'defaultCountdownDurationSeconds=$defaultCountdownDurationSeconds',
'defaultCountdownDurationSeconds=$defaultCountdownDurationSeconds'
'logScopeWeeks=$logScopeWeeks '
'showDistinctLogs=$showDistinctLogs '
'showWorkoutDuration=$showWorkoutDuration ',
);
}
@@ -92,13 +110,24 @@ class GymStateNotifier extends _$GymStateNotifier {
PREFS_COUNTDOWN_DURATION,
state.countdownDuration.inSeconds,
);
if (state.logScopeWeeks != null) {
await prefs.setInt(PREFS_LOG_SCOPE_WEEKS, state.logScopeWeeks!);
} else {
await prefs.remove(PREFS_LOG_SCOPE_WEEKS);
}
await prefs.setBool(PREFS_SHOW_DISTINCT_LOGS, state.showDistinctLogs);
await prefs.setBool(PREFS_SHOW_WORKOUT_DURATION, state.showWorkoutDuration);
_logger.finer(
'Saved preferences: '
'showExercise=${state.showExercisePages} '
'showTimer=${state.showTimerPages} '
'alertOnCountdownEnd=${state.alertOnCountdownEnd} '
'useCountdownBetweenSets=${state.useCountdownBetweenSets} '
'defaultCountdownDuration=${state.countdownDuration.inSeconds}',
'defaultCountdownDuration=${state.countdownDuration.inSeconds}'
'logScopeWeeks=${state.logScopeWeeks} '
'showDistinctLogs=${state.showDistinctLogs} '
'showWorkoutDuration=${state.showWorkoutDuration} ',
);
}
@@ -257,6 +286,8 @@ class GymStateNotifier extends _$GymStateNotifier {
routine: routine,
iteration: iteration,
currentPage: initialPage,
// A fresh workout also restarts the elapsed timer
workoutStart: shouldReset ? clock.now() : null,
);
// Calculate the pages.
@@ -279,9 +310,11 @@ class GymStateNotifier extends _$GymStateNotifier {
return;
}
final log = Log.fromSetConfigData(slotEntryPage.setConfigData!);
log.routineId = state.routine.id!;
log.iteration = state.iteration;
final log = Log.fromSetConfigData(
slotEntryPage.setConfigData!,
routineId: state.routine.id,
iteration: state.iteration,
);
ref.read(gymLogProvider.notifier).setLog(log);
}
@@ -312,6 +345,22 @@ class GymStateNotifier extends _$GymStateNotifier {
_savePrefs();
}
/// Passing null resets the scope to the current routine
void setLogScopeWeeks(int? weeks) {
state = state.copyWith(logScopeWeeks: weeks, clearLogScopeWeeks: weeks == null);
_savePrefs();
}
void setShowDistinctLogs(bool value) {
state = state.copyWith(showDistinctLogs: value);
_savePrefs();
}
void setShowWorkoutDuration(bool value) {
state = state.copyWith(showWorkoutDuration: value);
_savePrefs();
}
void markSlotPageAsDone(String uuid, {required bool isDone}) {
final slotPage = state.getSlotPageByUUID(uuid);
if (slotPage == null) {
@@ -419,6 +468,12 @@ class GymStateNotifier extends _$GymStateNotifier {
recalculateIndices();
}
/// Resets the workout start time to now, e.g. when the user taps "start"
void startWorkout() {
_logger.fine('Setting workout start time');
state = state.copyWith(workoutStart: clock.now());
}
void clear() {
_logger.fine('Clearing state');
state = state.copyWith(
@@ -427,7 +482,7 @@ class GymStateNotifier extends _$GymStateNotifier {
currentPage: 0,
validUntil: clock.now().add(DEFAULT_DURATION),
startTime: null,
workoutStart: clock.now(),
);
}
}

View File

@@ -40,7 +40,7 @@ final class GymStateNotifierProvider extends $NotifierProvider<GymStateNotifier,
}
}
String _$gymStateNotifierHash() => r'213315cfc2f3047fe99ab88e81ee7e570e7c6ec3';
String _$gymStateNotifierHash() => r'53db98cc8dacabe415f9986e8fae3fa745965c99';
abstract class _$GymStateNotifier extends $Notifier<GymModeState> {
GymModeState build();

View File

@@ -16,6 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:clock/clock.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:wger/features/routines/models/log.dart';
@@ -27,16 +28,44 @@ final workoutLogProvider = Provider<WorkoutLogMutations>((ref) {
return WorkoutLogMutations(ref.read(workoutLogRepositoryProvider));
});
/// Streams the past logs for [exerciseId] within [routineId], newest first.
/// Streams the past logs for [exerciseId], newest first.
///
/// Without [weeksBack] only the logs of [routineId] are returned. Setting it
/// widens the scope to all routines and instead limits the logs to the last
/// [weeksBack] weeks, in which case [routineId] is ignored. With [distinct],
/// only the newest log of each repetition/weight combination is kept.
@riverpod
Stream<List<Log>> pastExerciseLogs(
Ref ref, {
required int routineId,
required int exerciseId,
int? weeksBack,
bool distinct = true,
}) {
return ref
.read(workoutLogRepositoryProvider)
.watchLogsByExerciseDrift(routineId: routineId, exerciseId: exerciseId);
final repo = ref.read(workoutLogRepositoryProvider);
final cutoff = weeksBack != null ? clock.now().subtract(Duration(days: weeksBack * 7)) : null;
return repo
.watchLogsByExerciseDrift(
routineId: weeksBack == null ? routineId : null,
exerciseId: exerciseId,
since: cutoff,
)
.map((logs) => distinct ? _deduplicate(logs) : logs);
}
/// Keeps only the first log of each repetitions/weight combination, units included.
///
/// Expects [logs] to be sorted newest first, so the newest log of each
/// combination survives.
List<Log> _deduplicate(List<Log> logs) {
final seen = <(num?, int?, num?, int?)>{};
return logs
.where(
(log) => seen.add((log.repetitions, log.repetitionsUnitId, log.weight, log.weightUnitId)),
)
.toList();
}
class WorkoutLogMutations {

View File

@@ -8,20 +8,35 @@ part of 'workout_logs_notifier.dart';
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Streams the past logs for [exerciseId] within [routineId], newest first.
/// Streams the past logs for [exerciseId], newest first.
///
/// Without [weeksBack] only the logs of [routineId] are returned. Setting it
/// widens the scope to all routines and instead limits the logs to the last
/// [weeksBack] weeks, in which case [routineId] is ignored. With [distinct],
/// only the newest log of each repetition/weight combination is kept.
@ProviderFor(pastExerciseLogs)
final pastExerciseLogsProvider = PastExerciseLogsFamily._();
/// Streams the past logs for [exerciseId] within [routineId], newest first.
/// Streams the past logs for [exerciseId], newest first.
///
/// Without [weeksBack] only the logs of [routineId] are returned. Setting it
/// widens the scope to all routines and instead limits the logs to the last
/// [weeksBack] weeks, in which case [routineId] is ignored. With [distinct],
/// only the newest log of each repetition/weight combination is kept.
final class PastExerciseLogsProvider
extends $FunctionalProvider<AsyncValue<List<Log>>, List<Log>, Stream<List<Log>>>
with $FutureModifier<List<Log>>, $StreamProvider<List<Log>> {
/// Streams the past logs for [exerciseId] within [routineId], newest first.
/// Streams the past logs for [exerciseId], newest first.
///
/// Without [weeksBack] only the logs of [routineId] are returned. Setting it
/// widens the scope to all routines and instead limits the logs to the last
/// [weeksBack] weeks, in which case [routineId] is ignored. With [distinct],
/// only the newest log of each repetition/weight combination is kept.
PastExerciseLogsProvider._({
required PastExerciseLogsFamily super.from,
required ({int routineId, int exerciseId}) super.argument,
required ({int routineId, int exerciseId, int? weeksBack, bool distinct}) super.argument,
}) : super(
retry: null,
name: r'pastExerciseLogsProvider',
@@ -47,11 +62,14 @@ final class PastExerciseLogsProvider
@override
Stream<List<Log>> create(Ref ref) {
final argument = this.argument as ({int routineId, int exerciseId});
final argument =
this.argument as ({int routineId, int exerciseId, int? weeksBack, bool distinct});
return pastExerciseLogs(
ref,
routineId: argument.routineId,
exerciseId: argument.exerciseId,
weeksBack: argument.weeksBack,
distinct: argument.distinct,
);
}
@@ -66,12 +84,21 @@ final class PastExerciseLogsProvider
}
}
String _$pastExerciseLogsHash() => r'e2345fbf5c2bcbaa81a673d39212a59099de5424';
String _$pastExerciseLogsHash() => r'b700cebfb109d1a8ff651d5af76812aabf2eae81';
/// Streams the past logs for [exerciseId] within [routineId], newest first.
/// Streams the past logs for [exerciseId], newest first.
///
/// Without [weeksBack] only the logs of [routineId] are returned. Setting it
/// widens the scope to all routines and instead limits the logs to the last
/// [weeksBack] weeks, in which case [routineId] is ignored. With [distinct],
/// only the newest log of each repetition/weight combination is kept.
final class PastExerciseLogsFamily extends $Family
with $FunctionalFamilyOverride<Stream<List<Log>>, ({int routineId, int exerciseId})> {
with
$FunctionalFamilyOverride<
Stream<List<Log>>,
({int routineId, int exerciseId, int? weeksBack, bool distinct})
> {
PastExerciseLogsFamily._()
: super(
retry: null,
@@ -81,13 +108,25 @@ final class PastExerciseLogsFamily extends $Family
isAutoDispose: true,
);
/// Streams the past logs for [exerciseId] within [routineId], newest first.
/// Streams the past logs for [exerciseId], newest first.
///
/// Without [weeksBack] only the logs of [routineId] are returned. Setting it
/// widens the scope to all routines and instead limits the logs to the last
/// [weeksBack] weeks, in which case [routineId] is ignored. With [distinct],
/// only the newest log of each repetition/weight combination is kept.
PastExerciseLogsProvider call({
required int routineId,
required int exerciseId,
int? weeksBack,
bool distinct = true,
}) => PastExerciseLogsProvider._(
argument: (routineId: routineId, exerciseId: exerciseId),
argument: (
routineId: routineId,
exerciseId: exerciseId,
weeksBack: weeksBack,
distinct: distinct,
),
from: this,
);

View File

@@ -41,32 +41,44 @@ class WorkoutLogRepository {
WorkoutLogRepository(this._db);
/// Streams the logs for a single exercise within a routine, newest first,
/// with their repetition and weight units attached.
/// Streams the logs for a single exercise, newest first, with their
/// repetition and weight units attached.
///
/// Only logs belonging to [routineId] are returned, pass null for all
/// routines. [since] additionally restricts the result to logs on or after
/// that point in time.
Stream<List<Log>> watchLogsByExerciseDrift({
required int routineId,
int? routineId,
required int exerciseId,
DateTime? since,
}) {
_logger.finer('Watching local logs for routine $routineId, exercise $exerciseId');
_logger.finer(
'Watching local logs for exercise $exerciseId, '
'routine ${routineId ?? 'any'}, since ${since ?? 'always'}',
);
final query =
_db.select(_db.workoutLogTable).join([
leftOuterJoin(
_db.routineRepetitionUnitTable,
_db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId),
),
leftOuterJoin(
_db.routineWeightUnitTable,
_db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId),
),
])
..where(
_db.workoutLogTable.routineId.equals(routineId) &
_db.workoutLogTable.exerciseId.equals(exerciseId),
)
..orderBy([
OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc),
]);
final query = _db.select(_db.workoutLogTable).join([
leftOuterJoin(
_db.routineRepetitionUnitTable,
_db.routineRepetitionUnitTable.id.equalsExp(_db.workoutLogTable.repetitionsUnitId),
),
leftOuterJoin(
_db.routineWeightUnitTable,
_db.routineWeightUnitTable.id.equalsExp(_db.workoutLogTable.weightUnitId),
),
]);
var whereCondition = _db.workoutLogTable.exerciseId.equals(exerciseId);
if (routineId != null) {
whereCondition &= _db.workoutLogTable.routineId.equals(routineId);
}
if (since != null) {
whereCondition &= _db.workoutLogTable.date.isBiggerOrEqualValue(since);
}
query.where(whereCondition);
query.orderBy([
OrderingTerm(expression: _db.workoutLogTable.date, mode: OrderingMode.desc),
]);
return query.watch().map((rows) {
return rows.map((row) {
@@ -113,7 +125,9 @@ class WorkoutLogRepository {
final existing =
await (_db.select(_db.workoutSessionTable)
..where(
(t) => t.routineId.equals(log.routineId) & t.date.equalsValue(dayMidnightUtc),
(t) =>
t.routineId.equalsNullable(log.routineId) &
t.date.equalsValue(dayMidnightUtc),
)
..limit(1))
.getSingleOrNull();

View File

@@ -30,7 +30,7 @@ import 'package:wger/l10n/generated/app_localizations.dart';
class SessionForm extends ConsumerStatefulWidget {
final _logger = Logger('SessionForm');
final int _routineId;
final int? _routineId;
final int? _dayId;
/// The session to edit, or null to create a new one.

View File

@@ -0,0 +1,88 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
/// Shows the time elapsed since the start of the current workout.
///
/// Reads the start time from the shared gym state so that the value is
/// consistent across all gym mode pages and with the times logged in the
/// workout session.
class ElapsedWorkoutTimer extends ConsumerStatefulWidget {
const ElapsedWorkoutTimer({super.key});
/// Formats a duration as `m:ss`, or `h:mm:ss` from one hour onwards
static String format(Duration elapsed) {
final hours = elapsed.inHours;
final minutes = elapsed.inMinutes.remainder(60);
final seconds = elapsed.inSeconds.remainder(60);
final secondsStr = seconds.toString().padLeft(2, '0');
if (hours > 0) {
return '$hours:${minutes.toString().padLeft(2, '0')}:$secondsStr';
}
return '$minutes:$secondsStr';
}
@override
ConsumerState<ElapsedWorkoutTimer> createState() => _ElapsedWorkoutTimerState();
}
class _ElapsedWorkoutTimerState extends ConsumerState<ElapsedWorkoutTimer> {
late Timer _uiTimer;
late DateTime _now;
@override
void initState() {
super.initState();
_now = clock.now();
_uiTimer = Timer.periodic(const Duration(seconds: 1), (_) {
setState(() => _now = clock.now());
});
}
@override
void dispose() {
_uiTimer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final workoutStart = ref.watch(gymStateProvider).workoutStart;
final elapsed = _now.difference(workoutStart);
final style = Theme.of(context).textTheme.bodySmall;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.timer_outlined, size: 16, color: style?.color),
const SizedBox(width: 2),
Text(
ElapsedWorkoutTimer.format(elapsed.isNegative ? Duration.zero : elapsed),
style: style,
),
],
);
}
}

View File

@@ -24,6 +24,7 @@ import 'package:wger/core/formatting/formatting.dart';
import 'package:wger/core/snackbar.dart';
import 'package:wger/core/widgets/core.dart';
import 'package:wger/core/widgets/error.dart';
import 'package:wger/features/exercises/models/exercise.dart';
import 'package:wger/features/routines/models/log.dart';
import 'package:wger/features/routines/models/set_config_data.dart';
import 'package:wger/features/routines/models/slot_entry.dart';
@@ -79,6 +80,8 @@ class LogPage extends ConsumerWidget {
pastExerciseLogsProvider(
routineId: gymState.routine.id!,
exerciseId: setConfigData.exerciseId,
weeksBack: gymState.logScopeWeeks,
distinct: gymState.showDistinctLogs,
),
);
@@ -136,7 +139,11 @@ class LogPage extends ConsumerWidget {
if (slotEntryPage.setConfigData!.comment.isNotEmpty)
Text(slotEntryPage.setConfigData!.comment, textAlign: TextAlign.center),
const SizedBox(height: 10),
Expanded(child: _buildPastLogs(pastLogs)),
// Overriding the log scope from here is handled in a follow-up, the
// settings currently only live in the gym mode options.
// _LogScopeControls(gymState: gymState),
Expanded(child: _buildPastLogs(pastLogs, setConfigData.exercise)),
Padding(
padding: const EdgeInsets.all(10),
@@ -159,7 +166,7 @@ class LogPage extends ConsumerWidget {
}
/// Renders the previous logs for this exercise
Widget _buildPastLogs(AsyncValue<List<Log>> pastLogs) {
Widget _buildPastLogs(AsyncValue<List<Log>> pastLogs, Exercise exercise) {
if (pastLogs.hasError) {
_logger.warning('Could not load past logs', pastLogs.error, pastLogs.stackTrace);
// Scroll-wrap so the indicator fits this slim slot instead of overflowing.
@@ -168,7 +175,9 @@ class LogPage extends ConsumerWidget {
);
}
final logs = pastLogs.value ?? const <Log>[];
return logs.isEmpty ? const SizedBox.shrink() : LogsPastLogsWidget(pastLogs: logs);
return logs.isEmpty
? const SizedBox.shrink()
: LogsPastLogsWidget(pastLogs: logs, exercise: exercise);
}
}
@@ -229,9 +238,13 @@ class LogsPlatesWidget extends ConsumerWidget {
class LogsPastLogsWidget extends ConsumerWidget {
final List<Log> pastLogs;
/// The exercise the logs belong to, they only carry its ID
final Exercise exercise;
const LogsPastLogsWidget({
super.key,
required this.pastLogs,
required this.exercise,
});
@override
@@ -255,7 +268,7 @@ class LogsPastLogsWidget extends ConsumerWidget {
subtitle: Text(dateFormat.format(pastLog.date)),
trailing: const Icon(Icons.copy),
onTap: () {
logProvider.setLog(pastLog);
logProvider.setLog(pastLog, exercise: exercise);
ScaffoldMessenger.of(context).hideCurrentSnackBar();
showSnackbar(context, AppLocalizations.of(context).dataCopied);
},
@@ -404,3 +417,63 @@ class _LogFormWidgetState extends ConsumerState<LogFormWidget> {
);
}
}
// Compact inline controls for overriding the global log-scope settings. Kept
// around for the follow-up that lets the scope be changed from the log page.
//
// class _LogScopeControls extends ConsumerWidget {
// final GymModeState gymState;
//
// const _LogScopeControls({required this.gymState});
//
// @override
// Widget build(BuildContext context, WidgetRef ref) {
// final gymNotifier = ref.read(gymStateProvider.notifier);
// final i18n = AppLocalizations.of(context);
// final theme = Theme.of(context);
//
// return Padding(
// padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.spaceBetween,
// children: [
// Row(
// children: [
// Icon(Icons.history, size: 18, color: theme.colorScheme.primary),
// const SizedBox(width: 4),
// DropdownButton<int?>(
// value: gymState.logScopeWeeks,
// isDense: true,
// underline: const SizedBox.shrink(),
// style: theme.textTheme.bodySmall,
// onChanged: (value) => gymNotifier.setLogScopeWeeks(value),
// items: [
// DropdownMenuItem<int?>(
// value: null,
// child: Text(i18n.gymModeLogScopeCurrentRoutine),
// ),
// ...[8, 12, 25, 50].map(
// (w) => DropdownMenuItem<int?>(
// value: w,
// child: Text(i18n.gymModeLogScopeWeeks(w)),
// ),
// ),
// ],
// ),
// ],
// ),
// Row(
// children: [
// Text(i18n.gymModeDistinctLogs, style: theme.textTheme.bodySmall),
// Switch.adaptive(
// value: gymState.showDistinctLogs,
// onChanged: (v) => gymNotifier.setShowDistinctLogs(v),
// materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
// ),
// ],
// ),
// ],
// ),
// );
// }
// }

View File

@@ -20,6 +20,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:wger/core/consts.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/features/routines/widgets/gym_mode/elapsed_time.dart';
import 'package:wger/features/routines/widgets/gym_mode/workout_menu.dart';
import 'package:wger/theme/theme.dart';
@@ -73,11 +74,13 @@ class NavigationFooter extends ConsumerWidget {
final PageController _controller;
final bool showPrevious;
final bool showNext;
final bool showElapsedTime;
const NavigationFooter(
this._controller, {
this.showPrevious = true,
this.showNext = true,
this.showElapsedTime = true,
});
@override
@@ -98,6 +101,10 @@ class NavigationFooter extends ConsumerWidget {
)
else
const SizedBox(width: 48),
if (showElapsedTime && gymState.showWorkoutDuration) ...[
const ElapsedWorkoutTimer(),
const SizedBox(width: 8),
],
Expanded(
child: GestureDetector(
onTap: () => showDialog(

View File

@@ -75,7 +75,7 @@ class _SessionPageState extends ConsumerState<SessionPage> {
Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: SessionForm(
gymState.routine.id!,
gymState.routine.id,
onSaved: () => widget._controller.nextPage(
duration: DEFAULT_ANIMATION_DURATION,
curve: DEFAULT_ANIMATION_CURVE,

View File

@@ -1,13 +1,13 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2025 wger Team
* Copyright (c) 2020 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wger Workout Manager is distributed in the hope that it will be useful,
* 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 Affero General Public License for more details.
@@ -80,6 +80,14 @@ class _GymModeOptionsState extends ConsumerState<GymModeOptions> {
value: gymState.showExercisePages,
onChanged: (value) => gymNotifier.setShowExercisePages(value),
),
SwitchListTile(
key: const ValueKey('gym-mode-option-show-workout-duration'),
title: Text(i18n.gymModeShowWorkoutDuration),
value: gymState.showWorkoutDuration,
onChanged: (value) => gymNotifier.setShowWorkoutDuration(value),
),
const Divider(),
SwitchListTile(
key: const ValueKey('gym-mode-option-show-timer'),
title: Text(i18n.gymModeShowTimer),
@@ -149,6 +157,7 @@ class _GymModeOptionsState extends ConsumerState<GymModeOptions> {
enabled: gymState.showTimerPages && gymState.useCountdownBetweenSets,
),
),
SwitchListTile(
key: const ValueKey('gym-mode-notify-countdown'),
title: Text(i18n.gymModeNotifyOnCountdownFinish),
@@ -157,6 +166,36 @@ class _GymModeOptionsState extends ConsumerState<GymModeOptions> {
? (value) => gymNotifier.setAlertOnCountdownEnd(value)
: null,
),
const Divider(),
ListTile(
key: const ValueKey('gym-mode-log-scope'),
title: Text(i18n.gymModeLogScope),
subtitle: Text(i18n.gymModeLogScopeHelp),
trailing: DropdownButton<int?>(
key: const ValueKey('log-scope-dropdown'),
value: gymState.logScopeWeeks,
onChanged: (value) => gymNotifier.setLogScopeWeeks(value),
items: [
DropdownMenuItem<int?>(
value: null,
child: Text(i18n.gymModeLogScopeCurrentRoutine),
),
...[8, 12, 25, 50].map(
(weeks) => DropdownMenuItem<int?>(
value: weeks,
child: Text(i18n.gymModeLogScopeWeeks(weeks)),
),
),
],
),
),
SwitchListTile(
key: const ValueKey('gym-mode-distinct-logs'),
title: Text(i18n.gymModeDistinctLogs),
value: gymState.showDistinctLogs,
onChanged: (value) => gymNotifier.setShowDistinctLogs(value),
),
],
),
),
@@ -242,13 +281,14 @@ class StartPage extends ConsumerWidget {
FilledButton(
child: Text(AppLocalizations.of(context).start),
onPressed: () {
ref.read(gymStateProvider.notifier).startWorkout();
_controller.nextPage(
duration: const Duration(milliseconds: 200),
curve: Curves.bounceIn,
);
},
),
NavigationFooter(_controller, showPrevious: false),
NavigationFooter(_controller, showPrevious: false, showElapsedTime: false),
],
);
}

View File

@@ -55,7 +55,7 @@ class _SessionInfoState extends State<SessionInfo> {
),
if (editMode)
SessionForm(
widget._session.routineId!,
widget._session.routineId,
onSaved: () => setState(() => editMode = false),
session: widget._session,
)

View File

@@ -4,11 +4,11 @@
"@login": {
"description": "Text for login button"
},
"logout": "تسجيل خروج",
"logout": "تسجيل الخروج",
"@logout": {
"description": "Text for logout button"
},
"invalidUrl": "أدخل رابط صحيح من فضلك",
"invalidUrl": "الرجاء إدخال رابط صالح",
"@invalidUrl": {
"description": "Error message when the user enters an invalid URL, e.g. in the login form"
},
@@ -22,7 +22,7 @@
"description": "Error message when the user hasn't selected an ingredient from the autocompleter"
},
"logIngredient": "حفظ في مذكرة التغذيةسجل المكونات في دفتر التغذية",
"equipment": "الادوات",
"equipment": "المعدات",
"@equipment": {
"description": "Equipment needed to perform an exercise"
},
@@ -88,7 +88,7 @@
"@calves": {
"description": "Generated entry for translation for server strings"
},
"labelBottomNavWorkout": "تمرين",
"labelBottomNavWorkout": "التمرين",
"@labelBottomNavWorkout": {
"description": "Label used in bottom navigation, use a short word"
},
@@ -104,7 +104,7 @@
"noMeasurementEntries": "لا يوجد إدخالات قياس",
"password": "كلمة المرور",
"nutritionalPlan": "الخطة الغذائية",
"invalidUsername": "الرجاء كتابة اسم مستخدم صحيح",
"invalidUsername": "الرجاء إدخال اسم مستخدم صحيح",
"@invalidUsername": {
"description": "Error message when the user enters an invalid username"
},
@@ -135,7 +135,7 @@
}
}
},
"setNr": "مجموعة {nr}",
"setNr": "المجموعة {nr}",
"@setNr": {
"description": "Header in form indicating the number of the current set. Can also be translated as something like 'Set Nr. xy'.",
"type": "text",
@@ -169,7 +169,7 @@
"@total": {
"description": "Label used for total sums of e.g. calories or similar"
},
"dayDescriptionHelp": "وصف لما يتم القيام به في هذا اليوم (مثال، \"يوم السحب\") أو ما هي أجزاء الجسم التي سيتم تدريبها (مثال، \"الصدر والكتفين\")",
"dayDescriptionHelp": "وصف لما يتم القيام به في هذا اليوم (على سبيل المثال ’يوم السحب‘) أو ما هي أجزاء الجسم التي يتم تدريبها (على سبيل المثال ’الصدر والكتفين‘)",
"gymMode": "وضع النادي",
"@gymMode": {
"description": "Label when starting the gym mode"
@@ -192,17 +192,17 @@
"description": "Noun, not an imperative! Label used for the pause when using the gym mode"
},
"textPromptTitle": "مستعد للبدء ؟",
"success": "بنجاح",
"success": "نجاح",
"@success": {
"description": "Message when an action completed successfully, usually used as a heading"
},
"passwordTooShort": "كلمة المرور قصيرة",
"passwordTooShort": "كلمة المرور قصيرة جدًّا",
"@passwordTooShort": {
"description": "Error message when the user a password that is too short"
},
"repetitionUnit": "عدد التكرارات المتبقية",
"repetitionUnit": "وحدة التكرار",
"weightUnit": "وحدة الوزن",
"email": "البريد الإلكتروني",
"email": "عنوان البريد الإلكتروني",
"searchIngredient": "ابحث عن عنصر",
"@searchIngredient": {
"description": "Label on ingredient search form"
@@ -285,11 +285,11 @@
"@value": {
"description": "The value of a measurement entry"
},
"exercise": "تمرين",
"exercise": "التمرين",
"@exercise": {
"description": "An exercise for a workout"
},
"customServerHint": "ادخل عنوان الخادم خاصتك أو سيستخدم الخادم الافتراضي",
"customServerHint": "أدخل عنوان ملقّمك الخاص، وإلّا سيتم استخدام العنوان الافتراضي",
"@customServerHint": {
"description": "Hint text for the form where the users can enter their own wger instance"
},
@@ -343,7 +343,7 @@
"description": "Imperative. Label used in popup allowing the user to jump to a specific exercise while in the gym mode"
},
"difference": "الفرق",
"register": "تسجيل",
"register": "التسجيل",
"@register": {
"description": "Text for registration button"
},
@@ -369,7 +369,7 @@
"@searchExercise": {
"description": "Label on set form. Selected exercises are added to the set"
},
"noMatchingExerciseFound": "لم نجد تمرين بهذا الأسم",
"noMatchingExerciseFound": "لم يُعثر على تمارين مطابقة",
"@noMatchingExerciseFound": {
"description": "Message returned if no exercise match the searched string"
},
@@ -383,7 +383,7 @@
"@moreMeasurementEntries": {
"description": "Message shown when the user wants to add new measurement"
},
"usernameValidChars": "يجب أن يحتوي اسم المستخدم على كلاً من : أحرف، أرقام، رموز مثل @ ، + ، . ، - ، _",
"usernameValidChars": "لا يجوز أن يحتوي اسم المستخدم إلّا على أحرف وأرقام والرموز التالية: @، +، .، -، و _",
"@usernameValidChars": {
"description": "Error message when the user tries to register a username with forbidden characters"
},
@@ -426,7 +426,7 @@
"description": "Generated entry for translation for server strings"
},
"goToDetailPage": "الذهاب لصفحة التفاصيل",
"labelWorkoutLogs": "سجلات التمرين",
"labelWorkoutLogs": "سجلّات التمرين",
"@labelWorkoutLogs": {
"description": "(Workout) logs"
},
@@ -436,7 +436,7 @@
"@miles": {
"description": "Generated entry for translation for server strings"
},
"rirNotUsed": "عدد التكرارات المتبقية غير موجود",
"rirNotUsed": "لم يتم استخدام التكرارات في الاحتياط",
"@rirNotUsed": {
"description": "Label used in RiR slider when the RiR value is not used/saved for the current setting or log"
},
@@ -493,7 +493,7 @@
"@miles_per_hour": {
"description": "Generated entry for translation for server strings"
},
"labelDashboard": "لوحة العمليات",
"labelDashboard": "لوحة التحكم",
"@labelDashboard": {
"description": "Title for screen dashboard"
},
@@ -545,7 +545,7 @@
},
"measurementEntriesHelpText": "الوحدة المستخدمة لقياس الفئة مثل \"سم\" أو \"%\"",
"sugars": "سكريات",
"customServerUrl": "رابط عنصر wger",
"customServerUrl": "رابط مثيل wger",
"@customServerUrl": {
"description": "Label in the form where the users can enter their own wger instance"
},
@@ -558,7 +558,7 @@
"@measurements": {
"description": "Categories for the measurements such as biceps size, body fat, etc."
},
"reps": "التكرارات الفعالة",
"reps": "التكرارات",
"@reps": {
"description": "Shorthand for repetitions, used when space constraints are tighter"
},
@@ -628,7 +628,7 @@
"@weekAverage": {
"description": "Header for the column of '7 day average' nutritional values, i.e. what was logged last week"
},
"invalidEmail": "الرجاء كتابة بريد إلكتروني صحيح",
"invalidEmail": "الرجاء إدخال عنوان بريد إلكتروني صالح",
"@invalidEmail": {
"description": "Error message when the user enters an invalid email"
},
@@ -662,7 +662,7 @@
"@category": {
"description": "Category for an exercise, ingredient, etc."
},
"rir": "عدد التكرارات المتبقية",
"rir": "التكرارات في الاحتياط",
"@rir": {
"description": "Shorthand for Repetitions In Reserve"
},
@@ -714,9 +714,9 @@
"description": "Error message when the user enters an invalid API key"
},
"useUsernameAndPassword": "استخدم اسم المستخدم وكلمة المرور",
"selectAvailablePlates": "اختر من الاطباق المتوفرة",
"selectAvailablePlates": "اختر الأطباق المُتاحة",
"barWeight": "وزن القضيب الحديدي",
"useColors": "استخدم الالوان",
"useColors": "استخدام الألوان",
"apiTokenValidChars": "إن مفتاح ال API لا يمكن أن يحتوي غير الأحرف من a-f، أرقام من 0-9، ويحب أن تكون 40 محرف تماما",
"@apiTokenValidChars": {
"description": "Error message when the user tries to input a API key with forbidden characters"
@@ -768,38 +768,38 @@
"@toAddMealsToThePlanGoToNutritionalPlanDetails": {
"description": "Message shown to guide users to the nutritional plan details page to add meals"
},
"dashboardWidgets": "بطاقات اللوحة الرئيسية",
"noIngredientsDefined": "لم يتم تحديد المكونات بعد",
"dashboardWidgets": "عناصر لوحة التحكم",
"noIngredientsDefined": "لم يتم تحديد المكوّنات بعد",
"startDate": "تاريخ البدء",
"@startDate": {
"description": "The start date of a nutritional plan or routine"
},
"dayTypeCustom": "مخصص",
"dayTypeCustom": "مُخصّص",
"dayTypeEnom": "كل دقيقة في رأس الساعة",
"dayTypeAmrap": "أكبر عدد ممكن من الجولات",
"dayTypeHiit": "التدريب المتقطع عالي الكثافة",
"dayTypeHiit": "التدريب المتقطّع عالي الكثافة",
"dayTypeTabata": "تاباتا",
"dayTypeEdt": "التدريب على الكثافة المتزايدة",
"dayTypeRft": "جولات الوقت",
"dayTypeAfap": "ابعد ما يمكن",
"slotEntryTypeNormal": "اعتيادي",
"slotEntryTypeDropset": "مجموعة إسقاط",
"dayTypeRft": "جولات للوقت",
"dayTypeAfap": "بأسرع ما يمكن",
"slotEntryTypeNormal": "عادي",
"slotEntryTypeDropset": "المجموعة التنازلية",
"slotEntryTypePartial": "جزئي",
"slotEntryTypeForced": "قسري",
"slotEntryTypeTut": "وقت تحت التوتر",
"slotEntryTypeIso": "الثبات المتساوي",
"slotEntryTypeJump": "قفز",
"trophies": "الجوائز و الكؤوس",
"slotEntryTypeTut": "الوقت تحت الضغط",
"slotEntryTypeIso": "الثبات المتساوي القياس",
"slotEntryTypeJump": "القفز",
"trophies": "الجوائز",
"routines": "الروتينات",
"newRoutine": "روتين جديد",
"noRoutines": "ليس لديك روتينات",
"restTime": "وقت راحة",
"sets": "المجموات",
"noRoutines": "ليس لديك أي روتين",
"restTime": "وقت الراحة",
"sets": "المجموعات",
"@sets": {
"description": "The number of sets to be done for one exercise"
},
"useMetric": "استخدم الوحدات المترية (كيلو جرام) لوزن الجسم",
"exerciseNr": "تمرين {nr}",
"useMetric": "استخدام الوحدات المترية لوزن الجسم",
"exerciseNr": "التمرين {nr}",
"@exerciseNr": {
"description": "Header in form indicating the number of the current exercise. Can also be translated as something like 'Set Nr. xy'.",
"type": "text",
@@ -809,7 +809,7 @@
}
}
},
"supersetNr": "تمرين خارق {nr}",
"supersetNr": "التمرين الخارق {nr}",
"@supersetNr": {
"description": "Header in form indicating the number of the current exercise. Can also be translated as something like 'Superset Nr. xy'.",
"type": "text",
@@ -1114,6 +1114,81 @@
}
},
"searchLanguageAll": "كافة اللغات",
"refreshToken": "رمز التحديث",
"invalidRefreshToken": "الرجاء إدخال رمز تحديث صالح",
"@invalidRefreshToken": {
"description": "Error message when the user enters an invalid refresh token"
},
"refreshTokenValidChars": "يحتوي رمز التحديث على ثلاثة أجزاء مفصولة بنقاط (ترويسة.حمولة.توقيع)، كل منها يتكوّن من أحرف وأرقام و’-‘ و’_‘.",
"@refreshTokenValidChars": {
"description": "Error message when the user pastes a string that does not match the JWT shape"
},
"refreshTokenHelperText": "أنشئ رمز تحديث JWT على موقع wger الإلكتروني والصقه هنا. يفيد هذا عندما يكون ملقّمك خلف وكيل مصادقة أو عندما ترغب في تخطي عملية تسجيل الدخول المعتادة.",
"@refreshTokenHelperText": {
"description": "Helper text on the refresh-token paste field"
},
"mfaChallengeTitle": "المصادقة الثنائية",
"@mfaChallengeTitle": {
"description": "App bar title on the 2FA challenge screen"
},
"mfaChallengeTotpPrompt": "أدخل الرمز المكوّن من ٦ أرقام من تطبيق المصادقة الخاص بك",
"@mfaChallengeTotpPrompt": {
"description": "Helper text above the TOTP input field"
},
"mfaChallengeRecoveryPrompt": "أدخل أحد رموز الاسترداد الخاصة بك",
"@mfaChallengeRecoveryPrompt": {
"description": "Helper text above the recovery-code input field"
},
"mfaCodeLabel": "الرمز",
"@mfaCodeLabel": {
"description": "Label on the 2FA code input field"
},
"mfaInvalidCode": "الرجاء إدخال رمز",
"@mfaInvalidCode": {
"description": "Validation error when the 2FA code field is empty"
},
"mfaUseRecoveryCode": "استخدام رمز استردادٍ بدلًا من ذلك",
"@mfaUseRecoveryCode": {
"description": "Button that switches the 2FA challenge to recovery-code mode"
},
"mfaUseTotpCode": "استخدام رمز تطبيق مصادقة",
"@mfaUseTotpCode": {
"description": "Button that switches the 2FA challenge back to TOTP mode"
},
"mfaSubmit": "تحقُّق",
"@mfaSubmit": {
"description": "Submit button on the 2FA challenge screen"
},
"mfaUnsupportedFactor": "تم إعداد حسابك باستخدام عامل مصادقة ثانٍ لا يدعمه هذا التطبيق حاليًّا. يُرجى تسجيل الدخول عبر الموقع الإلكتروني.",
"@mfaUnsupportedFactor": {
"description": "Shown when the server reports only factor types the app cannot handle (e.g. webauthn)"
},
"manageAccountOnWeb": "إدارة الحساب على الويب",
"@manageAccountOnWeb": {
"description": "Label on a button that opens the user's preferences page on the wger website"
},
"manageAccountOnWebSubtitle": "غيّر كلمة مرورك، أو أعدّ المصادقة الثنائية، أو أدر رموز واجهة برمجة التطبيقات (API)، أو احذف حسابك.",
"@manageAccountOnWebSubtitle": {
"description": "Helper text below the 'Manage account on the web' button listing what is configurable there"
},
"advanced": "متقدّم",
"advancedSubtitle": "خيارات الملقّم والمصادقة",
"serverSectionLabel": "الملقّم",
"signInMethodSectionLabel": "طريقة تسجيل الدخول",
"serverOptionDefaultDetail": "الملقّم الرسمي",
"serverOptionSelfHostedTitle": "مُستضاف ذاتيًّا",
"serverOptionSelfHostedDetail": "اتصل بمثيلك الخاص",
"authOptionPasswordTitle": "اسم المستخدم وكلمة المرور",
"signInWithToken": "تسجيل الدخول باستخدام الرمز",
"tokenSubtitle": "أنشئ واحدًا على موقع wger الإلكتروني",
"newToWger": "هل أنت جديد على wger؟",
"alreadyHaveAccount": "هل لديك حساب بالفعل؟",
"tokenLabel": "الرمز",
"webHandoffLinkLabel": "خيارات تسجيل دخول أخرى",
"webHandoffLinkSubtitle": "تسجيل الدخول عبر وسائل التواصل الاجتماعي، مفتاح المرور، تسجيل الدخول المُوحّد",
"slotEntryTypeMyo": "ميو",
"slotEntryTypeWarmup": "التحمية",
"preview": "عرض مبدئي",
"endBeforeStart": "قيمة النهاية لا يمكن ان تكون قبل البداية",
"minLengthRoutine": "يجب أن يستمر الروتين لمدة لا تقل عن {number} أسبوعًا",
"maxLengthRoutine": "يمكن أن يستمر الروتين لمدة أقصاها {number} أسبوعًا"

View File

@@ -1149,6 +1149,7 @@
"syncStatusDialogTitle": "Synchronisierungsstatus",
"syncStatusLastSynced": "Letzte Synchronisierung",
"syncStatusErrorDetails": "Fehlerdetails",
"syncStatusStalledHint": "Die Verbindung zum Synchronisierungsdienst scheint blockiert zu werden. Möglicherweise stört ein VPN, Werbeblocker, Virenscanner oder eine Firewall in diesem Netzwerk.",
"sessionExpired": "Deine Sitzung ist abgelaufen, bitte melde dich erneut an",
"endBeforeStart": "Der Endwert darf nicht vor dem Startwert liegen",
"minLengthRoutine": "Die Routine muss mindestens {number} Wochen lang sein",
@@ -1171,5 +1172,11 @@
"healthSyncDescription": "Importiert Körpermesswerte aus Apple Health oder Health Connect",
"healthSyncSuccess": "{count} Messwerte aus Health importiert",
"health": "Gesundheit",
"healthSyncPermissionDenied": "Zugriff auf die Gesundheitsdaten wurde nicht gewährt"
"healthSyncPermissionDenied": "Zugriff auf die Gesundheitsdaten wurde nicht gewährt",
"gymModeLogScope": "Frühere Protokolle",
"gymModeLogScopeHelp": "Welche Protokolle beim Training als Referenz angezeigt werden",
"gymModeLogScopeCurrentRoutine": "Aktuelle Routine",
"gymModeLogScopeWeeks": "Letzte {weeks} Wochen",
"gymModeDistinctLogs": "Doppelte Werte ausblenden",
"gymModeShowWorkoutDuration": "Trainingsdauer anzeigen"
}

View File

@@ -351,6 +351,7 @@
},
"gymModeShowExercises": "Show exercise overview pages",
"gymModeShowTimer": "Show timer between sets",
"gymModeShowWorkoutDuration": "Show workout duration",
"gymModeTimerType": "Timer type",
"gymModeTimerTypeHelText": "If a set has pause time, a countdown is always used.",
"countdown": "Countdown",
@@ -412,6 +413,17 @@
"@addSet": {
"description": "Label for the button that adds a set (to a workout day)"
},
"gymModeLogScope": "Previous logs",
"gymModeLogScopeHelp": "Which logs to show as reference while training",
"gymModeLogScopeCurrentRoutine": "Current routine",
"gymModeLogScopeWeeks": "Last {weeks} weeks",
"@gymModeLogScopeWeeks": {
"placeholders": {
"weeks": { "type": "int" }
}
},
"gymModeDistinctLogs": "Hide duplicate values",
"addMeal": "Add meal",
"@addMeal": {},
"mealLogged": "Meal logged to diary",
@@ -1445,6 +1457,10 @@
"@syncStatusErrorDetails": {
"description": "Header of the expandable section in the sync status dialog that reveals the raw error message"
},
"syncStatusStalledHint": "The connection to the sync service seems to be blocked. A VPN, ad blocker, antivirus or firewall on this network may be interfering.",
"@syncStatusStalledHint": {
"description": "Hint shown in the sync status dialog when the app keeps connecting but never receives any sync data, which usually means something on the network is blocking the connection"
},
"filterNutriscore": "Nutri-Score filter",
"@filterNutriscore": {
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"

View File

@@ -1186,6 +1186,7 @@
"syncStatusDialogTitle": "Estado de sincronización",
"syncStatusLastSynced": "Última sincronización",
"syncStatusErrorDetails": "Detalles del error",
"syncStatusStalledHint": "La conexión con el servicio de sincronización parece estar bloqueada. Es posible que una VPN, un bloqueador de anuncios, un antivirus o un cortafuegos de esta red estén interfiriendo.",
"sessionExpired": "Tu sesión ha expirado, inicia sesión de nuevo",
"weightOrRepsRequired": "Introduce un peso, repeticiones o ambos",
"timeStartEndBothOrNeither": "Indica la hora de inicio y de fin, o deja ambas vacías",
@@ -1210,5 +1211,11 @@
"healthSyncDescription": "Importa medidas corporales desde Apple Health o Health Connect",
"healthSyncSuccess": "Se importaron {count} medidas de salud",
"health": "Salud",
"healthSyncPermissionDenied": "No se concedió el acceso a los datos de salud"
"healthSyncPermissionDenied": "No se concedió el acceso a los datos de salud",
"gymModeLogScope": "Registros anteriores",
"gymModeLogScopeHelp": "Qué registros mostrar como referencia durante el entrenamiento",
"gymModeLogScopeCurrentRoutine": "Rutina actual",
"gymModeLogScopeWeeks": "Últimas {weeks} semanas",
"gymModeDistinctLogs": "Ocultar valores duplicados",
"gymModeShowWorkoutDuration": "Mostrar la duración del entrenamiento"
}

View File

@@ -1157,6 +1157,7 @@
"syncStatusDialogTitle": "État de la synchronisation",
"syncStatusLastSynced": "Dernière synchronisation",
"syncStatusErrorDetails": "Détails de l'erreur",
"syncStatusStalledHint": "La connexion au service de synchronisation semble être bloquée. Un VPN, un bloqueur de publicités, un antivirus ou un pare-feu sur ce réseau interfère peut-être.",
"sessionExpired": "Votre session a expiré, veuillez vous reconnecter",
"weightOrRepsRequired": "Veuillez saisir un poids, des répétitions, ou les deux",
"timeStartEndBothOrNeither": "Indiquez l'heure de début et de fin, ou laissez les deux vides",
@@ -1181,5 +1182,11 @@
"healthSyncDescription": "Importe les mesures corporelles depuis Apple Santé ou Health Connect",
"healthSyncSuccess": "{count} mesures de santé importées",
"health": "Santé",
"healthSyncPermissionDenied": "L'accès aux données de santé n'a pas été autorisé"
"healthSyncPermissionDenied": "L'accès aux données de santé n'a pas été autorisé",
"gymModeLogScope": "Journaux précédents",
"gymModeLogScopeHelp": "Quels journaux afficher comme référence pendant l'entraînement",
"gymModeLogScopeCurrentRoutine": "Routine actuelle",
"gymModeLogScopeWeeks": "{weeks} dernières semaines",
"gymModeDistinctLogs": "Masquer les valeurs en double",
"gymModeShowWorkoutDuration": "Afficher la durée de l'entraînement"
}

View File

@@ -5,7 +5,7 @@
"@time": {
"description": "The time of a meal or workout"
},
"timeEnd": "Vrijeme završetka",
"timeEnd": "Vrijeme kraja",
"@timeEnd": {
"description": "The end time of a workout"
},
@@ -286,7 +286,7 @@
"@timeStart": {
"description": "The starting time of a workout"
},
"timeStartAhead": "Vrijeme početka ne može biti prije vremena završetka",
"timeStartAhead": "Vrijeme početka ne može biti prije vremena kraja",
"ingredient": "Sastojak",
"energy": "Energija",
"@energy": {
@@ -467,7 +467,7 @@
"@close": {
"description": "Translation for close"
},
"enterMinCharacters": "Upiši barem {min} znaka",
"enterMinCharacters": "Upiši barem {min} znakova",
"@enterMinCharacters": {
"description": "Error message when the user hasn't entered the minimum amount characters in a form",
"type": "text",
@@ -1193,6 +1193,203 @@
"@appLanguageSystem": {
"description": "Dropdown entry that follows the device system language"
},
"alreadyHaveAccount": "Već imaš račun?",
"tokenLabel": "Token",
"signInWithToken": "Prijavi se s tokenom",
"signInMethodSectionLabel": "Način prijave",
"advanced": "Napredno",
"advancedSubtitle": "Opcije servera i autentifikacije",
"serverSectionLabel": "Server",
"serverOptionDefaultDetail": "Službeni server",
"serverOptionSelfHostedTitle": "Vlastiti hosting",
"serverOptionSelfHostedDetail": "Poveži se na vlastitu instancu",
"authOptionPasswordTitle": "korisničko ime i lozinka",
"tokenSubtitle": "Generiraj jedan na wger web-stranici",
"mfaChallengeTitle": "Dvofaktorska autentifikacija",
"@mfaChallengeTitle": {
"description": "App bar title on the 2FA challenge screen"
},
"syncStatusLastSynced": "Zadnja sinkronizacija",
"@syncStatusLastSynced": {
"description": "Label in the sync status dialog above the timestamp of the last successful sync"
},
"refreshToken": "Token za osvježavanje",
"mfaCodeLabel": "Kod",
"@mfaCodeLabel": {
"description": "Label on the 2FA code input field"
},
"mfaInvalidCode": "Upiši kod",
"@mfaInvalidCode": {
"description": "Validation error when the 2FA code field is empty"
},
"mfaUseRecoveryCode": "Umjesto toga upiši kod za obnavljanje",
"@mfaUseRecoveryCode": {
"description": "Button that switches the 2FA challenge to recovery-code mode"
},
"mfaUseTotpCode": "Koristi kod aplikacije za autentifikaciju",
"@mfaUseTotpCode": {
"description": "Button that switches the 2FA challenge back to TOTP mode"
},
"mfaSubmit": "Potvrdi",
"@mfaSubmit": {
"description": "Submit button on the 2FA challenge screen"
},
"mfaUnsupportedFactor": "Tvoj je račun postavljen s drugim faktorom koji ova aplikacija još ne podržava. Prijavi se na web-stranici.",
"@mfaUnsupportedFactor": {
"description": "Shown when the server reports only factor types the app cannot handle (e.g. webauthn)"
},
"manageAccountOnWeb": "Upravljaj računom na webu",
"@manageAccountOnWeb": {
"description": "Label on a button that opens the user's preferences page on the wger website"
},
"manageAccountOnWebSubtitle": "Promijeni lozinku, postavi dvofaktorsku autentifikaciju, upravljaj API tokenima ili izbriši svoj račun.",
"@manageAccountOnWebSubtitle": {
"description": "Helper text below the 'Manage account on the web' button listing what is configurable there"
},
"invalidRefreshToken": "Upiši valjani token za osvježavanje",
"@invalidRefreshToken": {
"description": "Error message when the user enters an invalid refresh token"
},
"refreshTokenValidChars": "Token za osvježavanje sadrži tri segmenta odvojena točkama (header.payload.signature), a svaki se sastoji od slova, znamenki, spojnica (-) i podvlaka (_)",
"@refreshTokenValidChars": {
"description": "Error message when the user pastes a string that does not match the JWT shape"
},
"mfaChallengeTotpPrompt": "Upiši 6-znamenkasti kod iz tvoje aplikacije za autentifikaciju",
"@mfaChallengeTotpPrompt": {
"description": "Helper text above the TOTP input field"
},
"webHandoffLinkLabel": "Druge opcije za prijavu",
"webHandoffLinkSubtitle": "Prijava putem društvenih mreža, pristupni ključ, SSO",
"newToWger": "Koristiš wger po prvi put?",
"planDateRange": "od {startDate} do {endDate}",
"@planDateRange": {
"description": "Label for the start and end date range of a plan",
"placeholders": {
"startDate": {
"type": "String"
},
"endDate": {
"type": "String"
}
}
},
"planStartDate": "od {startDate}",
"@planStartDate": {
"description": "Label for the start date of a plan",
"placeholders": {
"startDate": {
"type": "String"
}
}
},
"otherLogs": "Drugi zapisi",
"@otherLogs": {
"description": "Other unassigned logs. Label for the pseudo-meal section that groups all nutritional diary entries not assigned to a specific meal"
},
"carbohydratesSugar": "Šećer (ugljikohidrati)",
"@carbohydratesSugar": {
"description": "Label for the carbohydrates sugar"
},
"errorRawSource": "Neobrađeni podaci",
"@errorRawSource": {
"description": "Tab label for showing an HTML error response in its raw (unrendered) form, opposite of 'Preview'."
},
"mfaChallengeRecoveryPrompt": "Upiši jedan od svojih kodova za oporavak",
"@mfaChallengeRecoveryPrompt": {
"description": "Helper text above the recovery-code input field"
},
"clearSearchTerm": "Izbriši pojam pretrage (tekst)",
"@clearSearchTerm": {
"description": "Tooltip for the icon-button that clears the ingredient search text field"
},
"ingredients": "Sastojci",
"@ingredients": {
"description": "Plural title for the ingredients overview screen"
},
"dietaryInformation": "Informacije o prehrani",
"aboutViewDocsTitle": "Otvori dokumentaciju",
"aboutViewLicensesTitle": "Prikaži licence",
"powerSyncUnreachableTitle": "Usluga sinkronizacije nije dostupna",
"settingsImageCacheDescription": "Predmemorija slika",
"settingsDataTitle": "Privatnost",
"settingsKeepDataOnLogout": "Sačuvaj podatke prilikom odjave",
"settingsKeepDataOnLogoutDescription": "Lokalna baza podataka ostaje na tvom uređaju sve dok se ne prijavi jedan drugi račun.",
"youAreOffline": "Nemaš vezu s internetom",
"syncStatusConnected": "Povezano",
"@syncStatusConnected": {
"description": "Tooltip on the sync icon when the app is online and idle (no upload or download in progress)"
},
"syncStatusConnecting": "Povezivanje",
"@syncStatusConnecting": {
"description": "Tooltip on the sync icon while the app is establishing a connection to the sync service"
},
"syncStatusDisconnected": "Nepovezano",
"@syncStatusDisconnected": {
"description": "Tooltip on the sync icon when the app has no active connection to the sync service"
},
"syncStatusUploading": "Prenosi se",
"@syncStatusUploading": {
"description": "Tooltip on the sync icon while local changes are being uploaded to the server"
},
"syncStatusDownloading": "Preuzima se",
"@syncStatusDownloading": {
"description": "Tooltip on the sync icon while remote changes are being downloaded from the server"
},
"syncStatusSyncing": "Sinkronizira se",
"@syncStatusSyncing": {
"description": "Tooltip on the sync icon when the app is uploading and downloading at the same time"
},
"syncStatusError": "Greška pri sinkronizaciji",
"@syncStatusError": {
"description": "Status label shown in the sync status dialog when the latest sync attempt failed"
},
"syncStatusDialogTitle": "Stanje sinkronizacijie",
"@syncStatusDialogTitle": {
"description": "Title of the dialog opened by tapping the sync icon in the app bar"
},
"syncStatusErrorDetails": "Detalji greške",
"@syncStatusErrorDetails": {
"description": "Header of the expandable section in the sync status dialog that reveals the raw error message"
},
"enterMaxCharacters": "Upiši maksimalno {max} znakova",
"@enterMaxCharacters": {
"description": "Error message when the user has entered more than the allowed amount of characters in a form",
"type": "text",
"placeholders": {
"max": {
"type": "String"
}
}
},
"serverUnreachableRetry": "Pokušaj ponovo",
"@serverUnreachableRetry": {
"description": "Button that re-runs the auto-login attempt against the saved server."
},
"increase": "Povećaj",
"@increase": {
"description": "Tooltip / screen-reader label for a button that increases a numeric input by one step"
},
"decrease": "Smanji",
"@decrease": {
"description": "Tooltip / screen-reader label for a button that decreases a numeric input by one step"
},
"sessionExpired": "Tvoja je sesija istekla. Prijavi se ponovo",
"@sessionExpired": {
"description": "Snackbar message shown when the saved login token is no longer valid"
},
"weightOrRepsRequired": "Upiši težinu, broj ponavljanja ili oboje",
"@weightOrRepsRequired": {
"description": "Validation error when both weight and repetitions are empty in a workout log"
},
"timeStartEndBothOrNeither": "Postavi vrijeme početka i vrijeme kraja ili ostavi oba polja prazna",
"@timeStartEndBothOrNeither": {
"description": "Validation error when only one of start/end time is set on a workout session"
},
"refreshTokenHelperText": "Generiraj JWT token za osvježavanje na wger web-stranici i zalijepi ga ovdje. Korisno kada se tvof server nalazi iza proxyja za autorizaciju ili kada želiš preskočiti uobičajeni tok prijave.",
"@refreshTokenHelperText": {
"description": "Helper text on the refresh-token paste field"
},
"powerSyncUnreachableContent": "Tvoj je wger server dostupan, ali (zasebna) usluga koja obrađuje izvanmrežnu sinkronizaciju ne odgovara. Ako pokrećeš vlastiti hosting za wger, provjeri konfiguraciju i provjeri je li PowerSync usluga ispravno radi.",
"endBeforeStart": "Vrijednost kraja ne može biti prije vrijednosti početka",
"minLengthRoutine": "Rutina mora trajati najmanje {number} tjedna",
"maxLengthRoutine": "Rutina mora trajati najviše {number} tjedna"

File diff suppressed because it is too large Load Diff

View File

@@ -1193,6 +1193,111 @@
"@appLanguageSystem": {
"description": "Dropdown entry that follows the device system language"
},
"refreshToken": "Token de atualização",
"invalidRefreshToken": "Por favor, insira um token de atualização válido",
"@invalidRefreshToken": {
"description": "Error message when the user enters an invalid refresh token"
},
"refreshTokenValidChars": "Um token de atualização possui três segmentos separados por pontos (cabeçalho.carga útil.assinatura), cada um composto por letras, dígitos, '-' e '_'",
"@refreshTokenValidChars": {
"description": "Error message when the user pastes a string that does not match the JWT shape"
},
"refreshTokenHelperText": "Gere um token de atualização JWT no site da wger e cole-o aqui. Isso é útil quando seu servidor está atrás de um proxy de autenticação ou quando você deseja ignorar o fluxo de login normal.",
"@refreshTokenHelperText": {
"description": "Helper text on the refresh-token paste field"
},
"mfaChallengeTitle": "Autenticação de dois fatores",
"@mfaChallengeTitle": {
"description": "App bar title on the 2FA challenge screen"
},
"mfaChallengeTotpPrompt": "Insira o código de 6 dígitos do seu aplicativo autenticador",
"@mfaChallengeTotpPrompt": {
"description": "Helper text above the TOTP input field"
},
"mfaChallengeRecoveryPrompt": "Digite um dos seus códigos de recuperação",
"@mfaChallengeRecoveryPrompt": {
"description": "Helper text above the recovery-code input field"
},
"mfaCodeLabel": "Código",
"@mfaCodeLabel": {
"description": "Label on the 2FA code input field"
},
"mfaInvalidCode": "Por favor, insira um código",
"@mfaInvalidCode": {
"description": "Validation error when the 2FA code field is empty"
},
"mfaUseRecoveryCode": "Use um código de recuperação em vez disso",
"@mfaUseRecoveryCode": {
"description": "Button that switches the 2FA challenge to recovery-code mode"
},
"mfaUseTotpCode": "Use um código de aplicativo autenticador",
"@mfaUseTotpCode": {
"description": "Button that switches the 2FA challenge back to TOTP mode"
},
"mfaSubmit": "Verificar",
"@mfaSubmit": {
"description": "Submit button on the 2FA challenge screen"
},
"mfaUnsupportedFactor": "Sua conta está configurada com um segundo fator que este aplicativo ainda não suporta. Por favor faça login no site.",
"@mfaUnsupportedFactor": {
"description": "Shown when the server reports only factor types the app cannot handle (e.g. webauthn)"
},
"manageAccountOnWeb": "Gerenciar conta na web",
"@manageAccountOnWeb": {
"description": "Label on a button that opens the user's preferences page on the wger website"
},
"manageAccountOnWebSubtitle": "Altere sua senha, configure a autenticação de dois fatores, gerencie tokens de API ou exclua sua conta.",
"@manageAccountOnWebSubtitle": {
"description": "Helper text below the 'Manage account on the web' button listing what is configurable there"
},
"advanced": "Avançado",
"advancedSubtitle": "Opções de servidor e autenticação",
"serverSectionLabel": "Servidor",
"signInMethodSectionLabel": "Método de login",
"serverOptionDefaultDetail": "O servidor oficial",
"serverOptionSelfHostedTitle": "Autohospedado",
"serverOptionSelfHostedDetail": "Conecte-se à sua própria instância",
"authOptionPasswordTitle": "Nome de usuário e senha",
"signInWithToken": "Entrar com token",
"tokenSubtitle": "Gere um no site wger",
"newToWger": "É novo no wger?",
"alreadyHaveAccount": "Já tem uma conta?",
"tokenLabel": "Token",
"webHandoffLinkLabel": "Outras opções de login",
"webHandoffLinkSubtitle": "Login social, senha ou SSO",
"clearSearchTerm": "Limpar termo de pesquisa (texto)",
"@clearSearchTerm": {
"description": "Tooltip for the icon-button that clears the ingredient search text field"
},
"ingredients": "Ingredientes",
"@ingredients": {
"description": "Plural title for the ingredients overview screen"
},
"planDateRange": "De {startDate} a {endDate}",
"@planDateRange": {
"description": "Label for the start and end date range of a plan",
"placeholders": {
"startDate": {
"type": "String"
},
"endDate": {
"type": "String"
}
}
},
"planStartDate": "A partir de {startDate}",
"@planStartDate": {
"description": "Label for the start date of a plan",
"placeholders": {
"startDate": {
"type": "String"
}
}
},
"otherLogs": "Outros registros",
"@otherLogs": {
"description": "Other unassigned logs. Label for the pseudo-meal section that groups all nutritional diary entries not assigned to a specific meal"
},
"endBeforeStart": "O valor final não pode ser anterior ao inicial",
"minLengthRoutine": "A rotina precisa durar pelo menos {number} semanas",
"maxLengthRoutine": "A rotina pode durar no máximo {number} semanas"

View File

@@ -26,6 +26,7 @@ import 'package:logging/logging.dart';
import 'package:powersync/powersync.dart';
import 'package:wger/core/error_dialogs.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/core/helpers.dart';
import 'package:wger/core/network/jwt.dart';
import 'package:wger/powersync/api_client.dart';
@@ -67,6 +68,9 @@ class DjangoConnector extends PowerSyncBackendConnector {
final String baseUrl;
final ApiClient apiClient;
/// Client for the endpoint liveness probes in [fetchCredentials].
final http.Client _probeClient;
/// IDs of CRUD operations that already triggered a user-facing
/// rejection dialog this session. Without this gate the same
/// permanent-failure op would re-pop the dialog on every sync tick
@@ -76,7 +80,35 @@ class DjangoConnector extends PowerSyncBackendConnector {
/// Resets on app restart.
final Set<String> _reportedFailedOps = {};
DjangoConnector({required this.baseUrl, required this.apiClient});
/// Spacing between repeated "backend unreachable" log lines while the
/// credential fetch keeps failing, so PowerSync's retry loop doesn't
/// flood the app logs during a longer outage.
static const unreachableLogInterval = Duration(minutes: 5);
/// When the current outage was last logged; null while the backend is
/// reachable.
DateTime? _lastUnreachableLogAt;
/// Endpoint last announced in the logs. [fetchCredentials] runs on every
/// token refresh, so the endpoint is only logged when it changes.
String? _lastLoggedEndpoint;
/// When "no live PowerSync endpoint" was last logged; null while an
/// endpoint resolves. Throttled like [_logUnreachable], since PowerSync
/// re-drives [fetchCredentials] on its retry schedule.
DateTime? _lastNoEndpointLogAt;
/// The `powersync_url` from the last token response and the endpoint it
/// resolved to. While the server keeps advertising the same URL, the cached
/// resolution is reused instead of re-probing on every token refresh (a dead
/// advertised URL would otherwise cost a probe timeout each time). A failed
/// resolution is never cached, so retries keep probing. Cleared on app
/// restart with the connector.
String? _lastProvidedUrl;
String? _lastResolvedEndpoint;
DjangoConnector({required this.baseUrl, required this.apiClient, http.Client? client})
: _probeClient = client ?? http.Client();
/// Get a token to authenticate against the PowerSync instance.
@override
@@ -90,23 +122,81 @@ class DjangoConnector extends PowerSyncBackendConnector {
// Backend unreachable (offline). Returning null skips this attempt;
// PowerSync retries on its own schedule. Without this, the raw
// SocketException stack trace floods the logs on every retry.
logger.fine('PowerSync credential fetch skipped, backend unreachable: ${e.message}');
_logUnreachable(e.message);
return null;
} on SocketException catch (e) {
logger.fine('PowerSync credential fetch skipped, backend unreachable: ${e.message}');
_logUnreachable(e.message);
return null;
}
_logReachableAgain();
final token = session['token'] as String;
final payload = decodeJwtPayload(token);
final provided = session['powersync_url'] as String?;
String? endpoint;
if (provided == _lastProvidedUrl && _lastResolvedEndpoint != null) {
endpoint = _lastResolvedEndpoint;
} else {
endpoint = await findLivePowerSyncUrl(
client: _probeClient,
serverUrl: baseUrl,
provided: provided,
);
if (endpoint != null) {
_lastProvidedUrl = provided;
_lastResolvedEndpoint = endpoint;
}
}
if (endpoint == null) {
// The wger backend answered (the token fetch above succeeded), so this
// is a bad or down sync service, not the device being offline.
// Returning null skips the attempt; PowerSync retries on its own.
_logNoEndpoint();
return null;
}
_lastNoEndpointLogAt = null;
if (endpoint != _lastLoggedEndpoint) {
logger.info('Connecting to PowerSync endpoint $endpoint');
_lastLoggedEndpoint = endpoint;
}
return PowerSyncCredentials(
endpoint: session['powersync_url'],
endpoint: endpoint,
token: token,
userId: payload?['sub']?.toString(),
expiresAt: jwtExp(payload),
expiresAt: jwtExpOnLocalClock(payload),
);
}
/// Logs a skipped credential fetch at INFO, throttled to once per [unreachableLogInterval]
/// per outage.
void _logUnreachable(String message) {
final now = DateTime.now();
final last = _lastUnreachableLogAt;
if (last == null || now.difference(last) >= unreachableLogInterval) {
logger.info('PowerSync credential fetch skipped, backend unreachable: $message');
_lastUnreachableLogAt = now;
}
}
/// Logs an unresolved PowerSync endpoint at WARNING, throttled to once per
/// [unreachableLogInterval] per outage.
void _logNoEndpoint() {
final now = DateTime.now();
final last = _lastNoEndpointLogAt;
if (last == null || now.difference(last) >= unreachableLogInterval) {
logger.warning('No PowerSync endpoint answered its liveness probe, skipping credentials');
_lastNoEndpointLogAt = now;
}
}
/// Closes an outage announced by [_logUnreachable], if any.
void _logReachableAgain() {
if (_lastUnreachableLogAt != null) {
logger.info('Backend reachable again, PowerSync credential fetch succeeded');
_lastUnreachableLogAt = null;
}
}
/// Date-only fields per table.
///
/// PowerSync serialises every SQLite `DateTime` column as an ISO-8601 timestamp

View File

@@ -0,0 +1,124 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:logging/logging.dart';
import 'package:powersync/powersync.dart' show SyncStatus;
final _logger = Logger('powersync');
/// Flags a sync stream that keeps reconnecting without ever delivering a
/// checkpoint.
///
/// That is the signature of a middlebox (VPN, ad blocker, antivirus, carrier
/// proxy) silently swallowing the long-lived stream request while short REST
/// requests still pass: the SDK sees a clean end-of-stream on every
/// iteration, so no exception is thrown, nothing is logged above FINE and
/// `SyncStatus.anyError` stays null. The UI shows "Connecting" forever
/// without a trace.
///
/// The watchdog arms a timer while the client wants to sync but has not
/// received a checkpoint in this connection epoch. Checkpoint progress
/// disarms it until [reset]; an active download or a surfaced error pauses
/// it (those cases are visible through other channels). If the timer
/// survives [timeout], [stalled] flips to true (the sync status dialog
/// shows a hint) and a WARNING lands in the app logs.
class SyncStreamWatchdog {
SyncStreamWatchdog({this.timeout = const Duration(minutes: 2)});
final Duration timeout;
/// True while the stream looks blocked. Consumed by the sync status dialog.
final ValueNotifier<bool> stalled = ValueNotifier(false);
Timer? _timer;
DateTime? _lastCheckpoint;
bool _sawStatus = false;
/// Set once a checkpoint arrived; the watchdog then stays quiet so a later
/// idle connection (status events stop while nothing changes) cannot
/// re-trigger it. [reset] re-arms for the next connection epoch.
bool _disarmed = false;
void onStatus(SyncStatus status) {
final checkpoint = status.lastSyncedAt;
// Progress is a NEW checkpoint: the first status event replays the
// timestamp persisted in the local DB (which may be weeks old on a
// blocked device), so only a change to a non-null value counts.
final madeProgress = _sawStatus && checkpoint != null && checkpoint != _lastCheckpoint;
_sawStatus = true;
_lastCheckpoint = checkpoint;
if (madeProgress) {
_disarmed = true;
_cancelTimer();
if (stalled.value) {
_logger.info('Sync stream recovered, checkpoint received');
stalled.value = false;
}
return;
}
// Downloading means data is flowing (a first checkpoint on a large
// account can take a while); an error is already surfaced by the sync
// status dialog. Neither is the silent failure we are watching for.
if (status.downloading || status.anyError != null) {
_cancelTimer();
return;
}
// A `connecting` flag briefly dropping between two retry iterations must
// NOT clear the timer: the silent connect/EOF loop would reset it on
// every cycle. Only [reset] (deliberate disconnect) clears it. While
// already stalled there is nothing new to detect (and no reason to log
// the warning again), so the timer stays off until recovery.
if (!_disarmed && !stalled.value && (status.connecting || status.connected)) {
_timer ??= Timer(timeout, _onTimeout);
}
}
/// Call when the app disconnects on purpose (offline gate, logout), so a
/// device that is simply offline is never reported as blocked.
void reset() {
_cancelTimer();
_disarmed = false;
stalled.value = false;
}
void dispose() {
_cancelTimer();
stalled.dispose();
}
void _onTimeout() {
_timer = null;
stalled.value = true;
_logger.warning(
'Sync stream keeps terminating without receiving any data. The '
'connection to the sync service may be blocked by a VPN, ad blocker, '
'antivirus or firewall on this network.',
);
}
void _cancelTimer() {
_timer?.cancel();
_timer = null;
}
}

View File

@@ -37,10 +37,10 @@ packages:
dependency: "direct main"
description:
name: app_links
sha256: "4ec328cd9fd51fd0e7eb8870a9612c1fde0f091901932238c4f4e60b5f7f1315"
sha256: f8db46d2ea9ff6f3a37191a7fd5b7813da1253ace8c32c1b9eadace41d1188ea
url: "https://pub.dev"
source: hosted
version: "7.1.2"
version: "7.2.1"
app_links_linux:
dependency: transitive
description:
@@ -53,10 +53,10 @@ packages:
dependency: transitive
description:
name: app_links_platform_interface
sha256: "78a18580eecac98108d1eef52a7db668bc317714f5205e616973363326efe333"
sha256: "7546f09a6e93f4a2df2fe2bd40a5c6c64310ac461b036d82b43033be7a59f809"
url: "https://pub.dev"
source: hosted
version: "2.0.3"
version: "2.0.4"
app_links_web:
dependency: transitive
description:
@@ -101,10 +101,10 @@ packages:
dependency: transitive
description:
name: build
sha256: a156715e7cd728130c592f30552575908aae5b100005fbc1f0fb16b3c03a3d10
sha256: "45d14a0fb23e018d8287c32fc98d726ce466b231928ed9b9200f29bd3ccd39ae"
url: "https://pub.dev"
source: hosted
version: "4.0.6"
version: "4.0.7"
build_config:
dependency: transitive
description:
@@ -125,10 +125,10 @@ packages:
dependency: "direct dev"
description:
name: build_runner
sha256: "1523ce62448ebac2c15a8ba5fbad8acac169788658a7dd2a1c2d9c2a9318b9a6"
sha256: "5367e521935b102bdf1e735d2aab461e36b2edca6517662d088dd04cc39f8d16"
url: "https://pub.dev"
source: hosted
version: "2.15.0"
version: "2.15.1"
built_collection:
dependency: transitive
description:
@@ -285,10 +285,10 @@ packages:
dependency: "direct main"
description:
name: connectivity_plus
sha256: cad0e811a289ea2a941119dc483c204ec1684cbb9a8fc7351fe4a230b8313160
sha256: "762c99f890ca8bf87f7337236f99edd42793843bc6c3631da294a76653a54bd0"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
version: "7.3.1"
connectivity_plus_platform_interface:
dependency: "direct dev"
description:
@@ -381,10 +381,10 @@ packages:
dependency: "direct main"
description:
name: drift
sha256: "6cc0b623c0e83f7080524d8396e9301b1d78b9c66a4fdceeb0f798211303254c"
sha256: "84688491040b0ceb26575709a84d701c84ad4df4d8aff020adf6d85f155fb0dd"
url: "https://pub.dev"
source: hosted
version: "2.34.0"
version: "2.34.2"
drift_dev:
dependency: "direct dev"
description:
@@ -405,10 +405,10 @@ packages:
dependency: "direct main"
description:
name: equatable
sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b"
sha256: "3bce007a596ff8b3119c45d68aaef631272537c03d30e5d4534dd24bf4c5eaa2"
url: "https://pub.dev"
source: hosted
version: "2.0.8"
version: "2.1.0"
extended_image:
dependency: "direct main"
description:
@@ -426,7 +426,7 @@ packages:
source: hosted
version: "5.0.1"
fake_async:
dependency: transitive
dependency: "direct dev"
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
@@ -804,10 +804,10 @@ packages:
dependency: "direct main"
description:
name: image_picker
sha256: "91c025426c2881c551100bce834e201c835a170151545f58d17da5180ca7d9ac"
sha256: d8402284df184bc05f4a2210c6c23983b0720f4cd87cbd05c5390a78af602667
url: "https://pub.dev"
source: hosted
version: "1.2.2"
version: "1.2.3"
image_picker_android:
dependency: transitive
description:
@@ -1089,10 +1089,10 @@ packages:
dependency: "direct main"
description:
name: package_info_plus
sha256: f5c435dc0e0d461e5b32471a870f769b6a1cc46930637efe24fbc535314e78ad
sha256: "127e1751e37ffb2ff4658beeaca77bad0c27bf5f932bd3a501c2296926d4b481"
url: "https://pub.dev"
source: hosted
version: "10.2.0"
version: "10.2.1"
package_info_plus_platform_interface:
dependency: transitive
description:
@@ -1209,10 +1209,10 @@ packages:
dependency: "direct main"
description:
name: powersync
sha256: "6c1ab4bf50ea4e93f5c33863d37e69c7d6cf7342338e95c30a9dd24210b1e501"
sha256: "11a43bd499ad9fe8b573e93a0f2702fe695f4f3c3d20c40306468c7d985a90ae"
url: "https://pub.dev"
source: hosted
version: "2.3.0"
version: "2.3.2"
powersync_flutter_libs:
dependency: transitive
description:
@@ -1454,18 +1454,18 @@ packages:
dependency: transitive
description:
name: sqlite3
sha256: "37356bcb56ce0d9404d602c41e4bdb7765e7e9732a3e47adb3d98c556a6abdad"
sha256: c73fd75df1332d76a6257f4823ae4df9c791f522b97e4a60cbcad214de1becf4
url: "https://pub.dev"
source: hosted
version: "3.3.3"
version: "3.5.0"
sqlite3_connection_pool:
dependency: transitive
description:
name: sqlite3_connection_pool
sha256: "9d2b3b398b03c96743fd071521fc665be73c33c9cd5c56d87196baff8d8b4398"
sha256: ad51972d37bdf82929888e4c85e722bd9a0b5ff8ad389f89b1b00d19603c0d2d
url: "https://pub.dev"
source: hosted
version: "0.2.6"
version: "0.2.7"
sqlite3_flutter_libs:
dependency: transitive
description:
@@ -1478,18 +1478,18 @@ packages:
dependency: transitive
description:
name: sqlite3_web
sha256: "183cd6e1523dd4c9097c0f8e8e3e92da2d852f9c680df441c53626444d6d8dce"
sha256: aa6af15ef8bf8551d3a84203e3cbc022990567372e46ef98f91bdb2018fcfb0e
url: "https://pub.dev"
source: hosted
version: "0.9.0"
version: "0.9.4"
sqlite_async:
dependency: transitive
description:
name: sqlite_async
sha256: "17176f00a10e5b8ba6e0205e42de1c15a94ff8762745fed19750b44b6bbd5649"
sha256: "83aff15d2bb3b296d35e15419a85c3207df3baca62b64b778958a59eb291502d"
url: "https://pub.dev"
source: hosted
version: "0.14.3"
version: "0.14.4"
sqlparser:
dependency: transitive
description:
@@ -1726,34 +1726,34 @@ packages:
dependency: "direct main"
description:
name: video_player
sha256: "48a7bdaa38a3d50ec10c78627abdbfad863fdf6f0d6e08c7c3c040cfd80ae36f"
sha256: "20ef311160e2ced020a62f38e4cc399a1bf289e722fc5fe37c9d7b18e44c9e8d"
url: "https://pub.dev"
source: hosted
version: "2.11.1"
version: "2.13.0"
video_player_android:
dependency: transitive
description:
name: video_player_android
sha256: "5d18d04084cc0cfc7afde39d0a308d4041e8ae6e9d5255bc086c263998dd1201"
sha256: "5121de08444d00363efdda630a69ad4d27a208a9f7586482d4909a44a1cdbc63"
url: "https://pub.dev"
source: hosted
version: "2.9.6"
version: "2.11.0"
video_player_avfoundation:
dependency: transitive
description:
name: video_player_avfoundation
sha256: "9338f3ec22774f88146b22f13273a446719b1da010fd200c4d1d97802156ac58"
sha256: c238f5f0a26845cd0bcc2956049b63065a4d3c40ddfc22c3414cd170bef7fff9
url: "https://pub.dev"
source: hosted
version: "2.9.7"
version: "2.11.0"
video_player_platform_interface:
dependency: transitive
description:
name: video_player_platform_interface
sha256: "16eaed5268c571c31840dc58ef8da5f0cd4db2a98490c3b8f1cf70122546c6e0"
sha256: "92c0fbabe20c788e71fd10d26cea998d0d253282e65d145aed0818731cf593ce"
url: "https://pub.dev"
source: hosted
version: "6.7.0"
version: "6.9.0"
video_player_web:
dependency: transitive
description:

View File

@@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
# - the version number is taken from the git tag vX.Y.Z
# - the build number is computed by reading the last one from the play store
# and increasing by one
version: 2.0.1+220
version: 2.0.2+230
environment:
sdk: '>=3.10.0 <4.0.0'
@@ -32,13 +32,13 @@ dependencies:
flutter_localizations:
sdk: flutter
app_links: ^7.1.2
app_links: ^7.2.1
carousel_slider: ^5.1.2
clock: ^1.1.2
collection: ^1.19.1
cupertino_icons: ^1.0.9
drift: ^2.34.0
equatable: ^2.0.8
drift: ^2.34.2
equatable: ^2.1.0
extended_image: ^10.0.1
fl_chart: ^1.2.0
flex_color_scheme: ^8.4.0
@@ -61,27 +61,27 @@ dependencies:
url: https://github.com/ytsni/health_bridge.git
ref: 51a567db9a97ccb15a9c1138aa4bcbdaf3d6c7b1
http: ^1.6.0
image_picker: ^1.2.2
image_picker: ^1.2.3
intl: ^0.20.2
json_annotation: ^4.12.0
markdown: ^7.3.1
multi_select_flutter: ^4.1.3
package_info_plus: ^10.2.0
package_info_plus: ^10.2.1
path: ^1.9.1
path_provider: ^2.1.6
shared_preferences: ^2.5.5
table_calendar: ^3.2.0
url_launcher: ^6.3.2
version: ^3.0.2
video_player: ^2.11.1
video_player: ^2.13.0
logging: ^1.3.0
flutter_riverpod: ^3.3.2
riverpod_annotation: ^4.0.3
drift_sqlite_async: ^0.3.1
stream_transform: ^2.1.1
state_notifier: ^1.0.0
connectivity_plus: ^7.2.0
powersync: ^2.3.0
connectivity_plus: ^7.3.1
powersync: ^2.3.2
dependency_overrides:
# health -> device_info_plus ^12.1.0 pins win32 5.x, which conflicts with
@@ -94,8 +94,9 @@ dev_dependencies:
sdk: flutter
integration_test:
sdk: flutter
build_runner: ^2.15.0
build_runner: ^2.15.1
cider: ^0.2.10
fake_async: ^1.3.1
# Used to stub the connectivity_plus platform interface
connectivity_plus_platform_interface: ^2.1.0
# Used to stub the url_launcher platform interface for the web-handoff test

View File

@@ -17,6 +17,9 @@
*/
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:logging/logging.dart';
import 'package:wger/core/helpers.dart';
void main() {
@@ -177,4 +180,154 @@ void main() {
});
});
});
group('findLivePowerSyncUrl', () {
const serverUrl = 'https://wger.example.com';
/// Client answering 200 only for the liveness probe of [liveEndpoint]
/// (with or without its trailing slash); records every requested URL.
MockClient liveOnlyAt(String liveEndpoint, [List<String>? requested]) {
final probe = '$liveEndpoint${liveEndpoint.endsWith('/') ? '' : '/'}probes/liveness';
return MockClient((request) async {
requested?.add(request.url.toString());
return request.url.toString() == probe
? http.Response('{"ready":true}', 200)
: http.Response('not found', 404);
});
}
test('uses the server-provided URL when it answers the probe', () async {
final requested = <String>[];
final client = liveOnlyAt('https://ps.example.com', requested);
expect(
await findLivePowerSyncUrl(
client: client,
serverUrl: serverUrl,
provided: 'https://ps.example.com',
),
'https://ps.example.com',
);
expect(requested, ['https://ps.example.com/probes/liveness']);
});
test('falls back to <serverUrl>/ps/ when the provided URL does not answer', () async {
// The #2432 shape: SITE_URL left at its localhost default, so the
// advertised URL points at the device itself.
expect(
await findLivePowerSyncUrl(
client: liveOnlyAt('$serverUrl/ps/'),
serverUrl: serverUrl,
provided: 'http://localhost/ps/',
),
'$serverUrl/ps/',
);
});
test('falls back when probing the provided URL throws', () async {
final client = MockClient((request) async {
if (request.url.host == 'ps.example.com') {
throw http.ClientException('Connection refused');
}
return http.Response('{"ready":true}', 200);
});
expect(
await findLivePowerSyncUrl(
client: client,
serverUrl: serverUrl,
provided: 'https://ps.example.com',
),
'$serverUrl/ps/',
);
});
test('probes only the fallback for a missing URL', () async {
final requested = <String>[];
final client = liveOnlyAt('$serverUrl/ps/', requested);
expect(
await findLivePowerSyncUrl(client: client, serverUrl: serverUrl, provided: null),
'$serverUrl/ps/',
);
expect(requested, ['$serverUrl/ps/probes/liveness']);
});
test('skips a URL without a scheme', () async {
final requested = <String>[];
final client = liveOnlyAt('$serverUrl/ps/', requested);
expect(
await findLivePowerSyncUrl(
client: client,
serverUrl: serverUrl,
provided: 'wger.example.com/ps/',
),
'$serverUrl/ps/',
);
expect(requested, ['$serverUrl/ps/probes/liveness']);
});
test('returns null when no candidate answers', () async {
expect(
await findLivePowerSyncUrl(
client: MockClient((_) async => http.Response('not found', 404)),
serverUrl: serverUrl,
provided: 'https://ps.example.com',
),
isNull,
);
});
test('logs failed probes at INFO with status code or exception', () async {
final records = <LogRecord>[];
final sub = Logger.root.onRecord.listen(records.add);
addTearDown(sub.cancel);
final client = MockClient((request) async {
if (request.url.host == 'ps.example.com') {
throw http.ClientException('Connection refused');
}
return http.Response('bad gateway', 502);
});
await findLivePowerSyncUrl(
client: client,
serverUrl: serverUrl,
provided: 'https://ps.example.com',
);
final messages = records.where((r) => r.level == Level.INFO).map((r) => r.message);
expect(
messages,
contains('PowerSync probe: https://ps.example.com/probes/liveness failed: '
'ClientException: Connection refused'),
);
expect(
messages,
contains('PowerSync probe: $serverUrl/ps/probes/liveness returned 502'),
);
});
test('keeps a sub-directory installation path in the fallback', () async {
expect(
await findLivePowerSyncUrl(
client: liveOnlyAt('https://example.com/wger/ps/'),
serverUrl: 'https://example.com/wger',
provided: null,
),
'https://example.com/wger/ps/',
);
});
test('handles a trailing slash on the server URL', () async {
expect(
await findLivePowerSyncUrl(
client: liveOnlyAt('$serverUrl/ps/'),
serverUrl: '$serverUrl/',
provided: null,
),
'$serverUrl/ps/',
);
});
});
}

View File

@@ -78,6 +78,7 @@ void main() {
final tMinAppVersion = Uri.parse('$serverUrl/api/v2/min-app-version/');
final tPowerSyncToken = Uri.parse('$serverUrl/api/v2/powersync-token');
final tLiveness = Uri.parse('${powerSyncUrl}probes/liveness');
final tFallbackLiveness = Uri.parse('$serverUrl/ps/probes/liveness');
final tIssueRefresh = Uri.parse('$serverUrl/api/v2/issue-refresh-token');
final tHeadlessRefresh = Uri.parse('$serverUrl/allauth/app/v1/tokens/refresh');
@@ -157,6 +158,10 @@ void main() {
);
when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('OK', 200));
// When the advertised URL fails its probe, the resolution falls back to
// <serverUrl>/ps/. A 404 keeps the "unreachable" scenarios unreachable;
// fallback-specific tests override this.
when(mockClient.get(tFallbackLiveness)).thenAnswer((_) async => Response('not found', 404));
// Default: the legacy-DRF → JWT migration POST silently fails as
// "offline" so existing tests that seed PREFS_USER fall through to the
@@ -447,11 +452,24 @@ void main() {
final state = await container.read(authProvider.future);
expect(state.status, AuthStatus.powerSyncUnreachable);
// Probe should never run if we can't resolve the URL.
// The unusable advertised URL is never probed; only the
// <serverUrl>/ps/ fallback is (dead here via the setUp default).
verifyNever(mockClient.get(tLiveness));
verify(mockClient.get(tFallbackLiveness)).called(1);
},
);
test('dead advertised URL but live <serverUrl>/ps/ fallback → loggedIn', () async {
when(mockClient.get(tLiveness)).thenAnswer((_) async => Response('Bad Gateway', 502));
when(mockClient.get(tFallbackLiveness)).thenAnswer((_) async => Response('OK', 200));
final container = makeContainer();
final state = await container.read(authProvider.future);
expect(state.status, AuthStatus.loggedIn);
expect(await PreferenceHelper.asyncPref.getBool(PREFS_HAS_EVER_SYNCED), true);
});
test('token endpoint returns 500 → powerSyncUnreachable', () async {
when(
mockClient.get(tPowerSyncToken, headers: anyNamed('headers')),

View File

@@ -82,4 +82,33 @@ void main() {
expect(jwtExp({'exp': 'soon'}), isNull);
});
});
group('jwtExpOnLocalClock', () {
test('anchors the token lifetime to the local clock', () {
// iat/exp lie far in the past; only their 600 s difference may matter.
final result = jwtExpOnLocalClock({'iat': 1700000000, 'exp': 1700000600});
final expected = DateTime.now().toUtc().add(const Duration(seconds: 600));
expect(result!.difference(expected).abs(), lessThan(const Duration(seconds: 5)));
});
test('falls back to the absolute exp when iat is missing', () {
expect(
jwtExpOnLocalClock({'exp': 1700000000}),
DateTime.utc(2023, 11, 14, 22, 13, 20),
);
});
test('falls back to the absolute exp when iat is not numeric', () {
expect(
jwtExpOnLocalClock({'iat': 'yesterday', 'exp': 1700000000}),
DateTime.utc(2023, 11, 14, 22, 13, 20),
);
});
test('returns null when payload is null or exp is missing', () {
expect(jwtExpOnLocalClock(null), isNull);
expect(jwtExpOnLocalClock({'iat': 1700000000}), isNull);
});
});
}

View File

@@ -19,6 +19,7 @@
import 'dart:async';
import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
@@ -180,6 +181,62 @@ void main() {
expect(container.read(networkStatusProvider), isFalse);
});
test('goes online immediately on a connectivity change, offline only after the probe', () async {
reachabilityCheck = (_, _, _) async => false;
final container = makeContainer(serverUrl: 'https://wger.example');
await container.read(networkStatusProvider.notifier).check();
expect(container.read(networkStatusProvider), isFalse);
// An adapter appears: optimistically online while the probe is pending.
final probeCompleter = Completer<bool>();
reachabilityCheck = (_, _, _) => probeCompleter.future;
connectivity.emit([ConnectivityResult.wifi]);
await pumpEventQueue();
expect(container.read(networkStatusProvider), isTrue);
// The failed probe downgrades the optimistic state again.
probeCompleter.complete(false);
await pumpEventQueue();
expect(container.read(networkStatusProvider), isFalse);
});
test('goes online optimistically when the app resumes from the background', () async {
reachabilityCheck = (_, _, _) async => false;
final container = makeContainer(serverUrl: 'https://wger.example');
await container.read(networkStatusProvider.notifier).check();
expect(container.read(networkStatusProvider), isFalse);
final probeCompleter = Completer<bool>();
reachabilityCheck = (_, _, _) => probeCompleter.future;
final binding = TestWidgetsFlutterBinding.instance;
binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await pumpEventQueue();
expect(container.read(networkStatusProvider), isTrue);
probeCompleter.complete(false);
await pumpEventQueue();
expect(container.read(networkStatusProvider), isFalse);
});
test('plain check stays pessimistic while the probe is pending', () async {
reachabilityCheck = (_, _, _) async => false;
final container = makeContainer(serverUrl: 'https://wger.example');
await container.read(networkStatusProvider.notifier).check();
expect(container.read(networkStatusProvider), isFalse);
// The periodic re-probe must not flash "online" while the backend is down.
final probeCompleter = Completer<bool>();
reachabilityCheck = (_, _, _) => probeCompleter.future;
final pending = container.read(networkStatusProvider.notifier).check();
await pumpEventQueue();
expect(container.read(networkStatusProvider), isFalse);
probeCompleter.complete(true);
expect(await pending, isTrue);
expect(container.read(networkStatusProvider), isTrue);
});
test('re-probes when invalidated (e.g. after login)', () async {
// NetworkStatus does not watch wgerBase, so auth re-probes the new server
// by invalidating the provider; the rebuild runs the probe again.

View File

@@ -16,15 +16,20 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:version/version.dart';
import 'package:wger/core/consts.dart';
import 'package:wger/core/network/auth_credential.dart';
import 'package:wger/core/network/auth_credentials_storage.dart';
import 'package:wger/core/network/secure_token_storage.dart';
import 'package:wger/core/network/server_gating.dart';
import '../../fake_auth_environment.dart';
/// The version gates don't touch storage; this stand-in satisfies the
/// constructor without pulling in secure-storage plumbing.
class _FakeSecureTokenStorage extends Fake implements SecureTokenStorage {}
@@ -35,6 +40,9 @@ ServerGating _gatingReturning(http.Response response) => ServerGating(
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
installFakeAuthEnvironment();
group('min server version check', () {
final minVersion = Version.parse(MIN_SERVER_VERSION);
final aboveMin = Version(minVersion.major, minVersion.minor + 1, 0).toString();
@@ -129,4 +137,88 @@ void main() {
expect(await gating.applicationUpdateRequired(serverUrl, '1.0.0'), true);
});
});
group('isPowerSyncReachable', () {
const serverUrl = 'https://wger.example.com';
const credential = AuthCredential.legacy('abc123');
/// Gating whose token endpoint answers [tokenBody] and whose liveness
/// probes answer 200 only for [liveUrl]. Every requested URL is
/// recorded in [requested].
ServerGating gatingWithTokenResponse(
Map<String, dynamic> tokenBody,
String liveUrl,
List<String> requested,
) => ServerGating(
MockClient((request) async {
requested.add(request.url.toString());
if (request.url.path.endsWith('/powersync-token')) {
return http.Response(json.encode(tokenBody), 200);
}
if (request.url.toString() == liveUrl) {
return http.Response('{"ready":true}', 200);
}
return http.Response('not found', 404);
}),
AuthCredentialsStorage(_FakeSecureTokenStorage()),
);
test('probes the server-provided powersync_url', () async {
final requested = <String>[];
final gating = gatingWithTokenResponse(
{'token': 't', 'powersync_url': 'https://ps.example.com'},
'https://ps.example.com/probes/liveness',
requested,
);
expect(
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
true,
);
expect(requested, contains('https://ps.example.com/probes/liveness'));
});
test('falls back to <serverUrl>/ps/ when powersync_url points at loopback', () async {
final requested = <String>[];
final gating = gatingWithTokenResponse(
{'token': 't', 'powersync_url': 'http://localhost/ps/'},
'$serverUrl/ps/probes/liveness',
requested,
);
expect(
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
true,
);
expect(requested, contains('$serverUrl/ps/probes/liveness'));
});
test('falls back to <serverUrl>/ps/ when powersync_url is missing', () async {
final requested = <String>[];
final gating = gatingWithTokenResponse(
{'token': 't'},
'$serverUrl/ps/probes/liveness',
requested,
);
expect(
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
true,
);
expect(requested, contains('$serverUrl/ps/probes/liveness'));
});
test('returns false when the resolved URL does not answer the probe', () async {
final gating = gatingWithTokenResponse(
{'token': 't', 'powersync_url': 'https://ps.example.com'},
'https://somewhere-else.example.com/probes/liveness',
<String>[],
);
expect(
await gating.isPowerSyncReachable(serverUrl: serverUrl, credential: credential),
false,
);
});
});
}

View File

@@ -1371,6 +1371,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String get gymModeShowWorkoutDuration =>
(super.noSuchMethod(
Invocation.getter(#gymModeShowWorkoutDuration),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#gymModeShowWorkoutDuration),
),
)
as String);
@override
String get gymModeTimerType =>
(super.noSuchMethod(
@@ -1596,6 +1607,50 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String get gymModeLogScope =>
(super.noSuchMethod(
Invocation.getter(#gymModeLogScope),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#gymModeLogScope),
),
)
as String);
@override
String get gymModeLogScopeHelp =>
(super.noSuchMethod(
Invocation.getter(#gymModeLogScopeHelp),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#gymModeLogScopeHelp),
),
)
as String);
@override
String get gymModeLogScopeCurrentRoutine =>
(super.noSuchMethod(
Invocation.getter(#gymModeLogScopeCurrentRoutine),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#gymModeLogScopeCurrentRoutine),
),
)
as String);
@override
String get gymModeDistinctLogs =>
(super.noSuchMethod(
Invocation.getter(#gymModeDistinctLogs),
returnValue: _i3.dummyValue<String>(
this,
Invocation.getter(#gymModeDistinctLogs),
),
)
as String);
@override
String get addMeal =>
(super.noSuchMethod(
@@ -4811,6 +4866,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations {
)
as String);
@override
String gymModeLogScopeWeeks(int? weeks) =>
(super.noSuchMethod(
Invocation.method(#gymModeLogScopeWeeks, [weeks]),
returnValue: _i3.dummyValue<String>(
this,
Invocation.method(#gymModeLogScopeWeeks, [weeks]),
),
)
as String);
@override
String planDateRange(String? startDate, String? endDate) =>
(super.noSuchMethod(

View File

@@ -16,9 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// SyncStatus constructor is marked as @internal
// ignore_for_file: invalid_use_of_internal_member
import 'dart:io' show SocketException;
import 'package:flutter/material.dart';
@@ -35,6 +32,8 @@ import 'package:wger/l10n/generated/app_localizations.dart';
import 'package:wger/l10n/generated/app_localizations_en.dart';
import 'package:wger/powersync/connector.dart' show RetryableUploadException;
import '../../helpers/sync_status.dart';
Widget _wrap(Widget child) {
return MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
@@ -55,26 +54,26 @@ void main() {
group('syncStatusIconAndLabel', () {
test('idle, online → Connected + cloud_done', () {
final r = syncStatusIconAndLabel(const SyncStatus(connected: true), i18n);
final r = syncStatusIconAndLabel(buildSyncStatus(connected: true), i18n);
expect(r.icon, Icons.cloud_done_outlined);
expect(r.label, i18n.syncStatusConnected);
});
test('connecting → Connecting + cloud_queue', () {
final r = syncStatusIconAndLabel(const SyncStatus(connecting: true), i18n);
final r = syncStatusIconAndLabel(buildSyncStatus(connecting: true), i18n);
expect(r.icon, Icons.cloud_queue);
expect(r.label, i18n.syncStatusConnecting);
});
test('disconnected → Disconnected + cloud_off', () {
final r = syncStatusIconAndLabel(const SyncStatus(), i18n);
final r = syncStatusIconAndLabel(buildSyncStatus(), i18n);
expect(r.icon, Icons.cloud_off);
expect(r.label, i18n.syncStatusDisconnected);
});
test('uploading only → Uploading + cloud_upload', () {
final r = syncStatusIconAndLabel(
const SyncStatus(connected: true, uploading: true),
buildSyncStatus(connected: true, uploading: true),
i18n,
);
expect(r.icon, Icons.cloud_upload_outlined);
@@ -83,7 +82,7 @@ void main() {
test('downloading only → Downloading + cloud_download', () {
final r = syncStatusIconAndLabel(
const SyncStatus(connected: true, downloading: true),
buildSyncStatus(connected: true, downloading: true),
i18n,
);
expect(r.icon, Icons.cloud_download_outlined);
@@ -92,7 +91,7 @@ void main() {
test('uploading + downloading → Synchronizing + cloud_sync', () {
final r = syncStatusIconAndLabel(
const SyncStatus(connected: true, uploading: true, downloading: true),
buildSyncStatus(connected: true, uploading: true, downloading: true),
i18n,
);
expect(r.icon, Icons.cloud_sync_outlined);
@@ -101,7 +100,7 @@ void main() {
test('error while connected → Sync error + sync_problem', () {
final r = syncStatusIconAndLabel(
SyncStatus(connected: true, downloadError: Exception('boom')),
buildSyncStatus(connected: true, downloadError: Exception('boom')),
i18n,
);
expect(r.icon, Icons.sync_problem);
@@ -110,7 +109,7 @@ void main() {
test('error while disconnected → Sync error + cloud_off', () {
final r = syncStatusIconAndLabel(
SyncStatus(downloadError: Exception('boom')),
buildSyncStatus(downloadError: Exception('boom')),
i18n,
);
expect(r.icon, Icons.cloud_off);
@@ -120,7 +119,7 @@ void main() {
group('SyncStatusDialog rendering', () {
testWidgets('renders title, status label, and "never synced" placeholder', (tester) async {
await _pumpDialog(tester, const SyncStatus(connected: true));
await _pumpDialog(tester, buildSyncStatus(connected: true));
expect(find.text(i18n.syncStatusDialogTitle), findsOneWidget);
expect(find.text(i18n.syncStatusConnected), findsOneWidget);
@@ -130,23 +129,55 @@ void main() {
testWidgets('formats the last-sync timestamp when set', (tester) async {
final lastSync = DateTime.utc(2025, 1, 15, 9, 30, 45);
await _pumpDialog(tester, SyncStatus(connected: true, lastSyncedAt: lastSync));
await _pumpDialog(tester, buildSyncStatus(connected: true, lastSyncedAt: lastSync));
expect(find.text('-/-'), findsNothing);
expect(find.textContaining('2025'), findsOneWidget);
});
testWidgets('omits the error expander when there is no error', (tester) async {
await _pumpDialog(tester, const SyncStatus(connected: true));
await _pumpDialog(tester, buildSyncStatus(connected: true));
expect(find.byType(ExpansionTile), findsNothing);
expect(find.text(i18n.syncStatusErrorDetails), findsNothing);
});
testWidgets('shows the blocked-connection hint when stalled without an error', (tester) async {
await tester.pumpWidget(
_wrap(SyncStatusDialog(buildSyncStatus(connecting: true), stalled: true)),
);
await tester.pumpAndSettle();
expect(find.text(i18n.syncStatusStalledHint), findsOneWidget);
expect(find.text(i18n.applicationLogs), findsOneWidget);
});
testWidgets('omits the stalled hint when not stalled', (tester) async {
await _pumpDialog(tester, buildSyncStatus(connecting: true));
expect(find.text(i18n.syncStatusStalledHint), findsNothing);
expect(find.text(i18n.applicationLogs), findsNothing);
});
testWidgets('prefers the real error over the stalled hint', (tester) async {
await tester.pumpWidget(
_wrap(
SyncStatusDialog(
buildSyncStatus(connecting: true, downloadError: Exception('boom')),
stalled: true,
),
),
);
await tester.pumpAndSettle();
expect(find.text(i18n.syncStatusStalledHint), findsNothing);
expect(find.text(i18n.syncStatusError), findsOneWidget);
});
testWidgets('renders the expander with the raw error message when present', (tester) async {
await _pumpDialog(
tester,
SyncStatus(connected: true, downloadError: Exception('disk-on-fire')),
buildSyncStatus(connected: true, downloadError: Exception('disk-on-fire')),
);
expect(find.byType(ExpansionTile), findsOneWidget);
@@ -161,7 +192,7 @@ void main() {
group('SyncStatusDialog error categorisation', () {
Future<void> expectCategory(WidgetTester tester, Object error, String? category) async {
await _pumpDialog(tester, SyncStatus(connected: true, downloadError: error));
await _pumpDialog(tester, buildSyncStatus(connected: true, downloadError: error));
if (category == null) {
for (final candidate in const [
'Authentication error',

View File

@@ -17,6 +17,7 @@
*/
import 'package:connectivity_plus_platform_interface/connectivity_plus_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'package:wger/core/network/network_provider.dart';
@@ -36,6 +37,8 @@ import 'package:wger/core/network/network_provider.dart';
/// Call once per test file (top of `main()` is fine, the static swaps stick
/// for the entire file).
void installFakeConnectivity() {
// NetworkStatus registers an AppLifecycleListener, which needs a binding.
TestWidgetsFlutterBinding.ensureInitialized();
ConnectivityPlatform.instance = _FakeConnectivityPlatform();
reachabilityCheck = (_, _, _) async => true;
}

View File

@@ -334,6 +334,10 @@ void main() {
await tester.pumpAndSettle();
// Act
// The card overflows the default 800x600 test surface and clips the
// ADVANCED footer at the bottom, so scroll it into view before tapping.
await tester.ensureVisible(find.byKey(const Key('advancedButton')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('advancedButton')));
await tester.pumpAndSettle();
await tester.tap(find.text('Refresh token'));
@@ -382,6 +386,10 @@ void main() {
await tester.pumpAndSettle();
// Act
// The card overflows the default 800x600 test surface and clips the
// ADVANCED footer at the bottom, so scroll it into view before tapping.
await tester.ensureVisible(find.byKey(const Key('advancedButton')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('advancedButton')));
await tester.pumpAndSettle();
await tester.tap(find.text('Refresh token'));

View File

@@ -23,6 +23,8 @@ import 'package:wger/features/exercises/models/exercise.dart';
import 'package:wger/features/routines/models/log.dart';
import 'package:wger/features/routines/models/set_config_data.dart';
import '../../../../test_data/exercises.dart';
void main() {
group('Log.volume', () {
test('returns weight * repetitions for metric (kg) and repetition unit', () {
@@ -199,6 +201,40 @@ void main() {
});
});
group('Log exercise hydration', () {
/// A log as it comes out of the database, with only the exercise ID set
Log makeDriftLog() => Log(
id: 'log-1',
exerciseId: 1,
routineId: 100,
weight: 20,
repetitions: 10,
date: DateTime(2026, 1, 1),
);
test('copies a log whose exercise was never hydrated', () {
final copy = makeDriftLog().copyWith(date: DateTime(2026, 2, 2));
expect(copy.exerciseObjOrNull, isNull);
});
test('reading an unhydrated exercise throws a descriptive error', () {
expect(
() => makeDriftLog().exerciseObj,
throwsA(isA<StateError>().having((e) => e.message, 'message', contains('log-1'))),
);
});
test('propagates the exercise when it is hydrated', () {
final log = makeDriftLog()..exercise = testBenchPress;
final copy = log.copyWith(weight: 30);
expect(copy.exerciseObj.id, testBenchPress.id);
expect(copy.exerciseId, testBenchPress.id);
});
});
group('Test the workout log model', () {
late Log log1;
late Log log2;

View File

@@ -41,8 +41,6 @@ void main() {
num repetitions = 10,
DateTime? date,
}) {
// Log.copyWith reads exerciseObj internally, so it must be set before
// setLog (which calls copyWith) is invoked.
return Log(
id: id ?? 'log-1',
exerciseId: exerciseId,
@@ -50,13 +48,29 @@ void main() {
weight: weight,
repetitions: repetitions,
date: date ?? DateTime.utc(2020, 1, 1),
)..exerciseObj = testBenchPress;
);
}
test('initial state is null', () {
expect(container.read(gymLogProvider), isNull);
});
test('setLog accepts a log with no exercise, as read from the database', () {
container.read(gymLogProvider.notifier).setLog(makeLog());
final state = container.read(gymLogProvider)!;
expect(state.exerciseId, 1);
expect(state.exerciseObjOrNull, isNull);
});
test('setLog hydrates the exercise when the caller passes one', () {
container.read(gymLogProvider.notifier).setLog(makeLog(), exercise: testBenchPress);
final state = container.read(gymLogProvider)!;
expect(state.exerciseObj.id, testBenchPress.id);
expect(state.exerciseId, testBenchPress.id);
});
test('setLog stores a copy with cleared id/sessionId and the current clock as date', () {
final fixed = DateTime.utc(2026, 5, 1, 12);
withClock(Clock.fixed(fixed), () {

View File

@@ -16,8 +16,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
import 'package:wger/core/shared_preferences.dart';
import 'package:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
@@ -29,6 +34,9 @@ void main() {
late ProviderContainer container;
setUp(() {
TestWidgetsFlutterBinding.ensureInitialized();
SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty();
container = ProviderContainer.test();
notifier = container.read(gymStateProvider.notifier);
notifier.state = notifier.state.copyWith(
@@ -274,4 +282,119 @@ void main() {
expect(notifier.state.totalPages, 11);
});
});
group('GymStateNotifier.setLogScopeWeeks', () {
test('Sets the scope and persists it', () async {
// Act
notifier.setLogScopeWeeks(12);
await pumpEventQueue();
// Assert
expect(notifier.state.logScopeWeeks, 12);
expect(await PreferenceHelper.asyncPref.getInt(PREFS_LOG_SCOPE_WEEKS), 12);
});
test('Resets the scope to the current routine', () async {
// Arrange
notifier.setLogScopeWeeks(12);
await pumpEventQueue();
// Act
notifier.setLogScopeWeeks(null);
await pumpEventQueue();
// Assert
expect(notifier.state.logScopeWeeks, isNull);
expect(await PreferenceHelper.asyncPref.getInt(PREFS_LOG_SCOPE_WEEKS), isNull);
});
});
group('GymStateNotifier.setShowWorkoutDuration', () {
test('Sets the flag and persists it', () async {
// Act
notifier.setShowWorkoutDuration(false);
await pumpEventQueue();
// Assert
expect(notifier.state.showWorkoutDuration, false);
expect(await PreferenceHelper.asyncPref.getBool(PREFS_SHOW_WORKOUT_DURATION), false);
});
});
group('GymStateNotifier.startWorkout', () {
test('Resets the workout start time to now', () {
// Arrange
notifier.state = notifier.state.copyWith(workoutStart: DateTime(2024, 5, 1, 10, 0));
// Act
withClock(Clock.fixed(DateTime(2024, 5, 1, 17, 30, 21)), () {
notifier.startWorkout();
});
// Assert
expect(notifier.state.workoutStart, DateTime(2024, 5, 1, 17, 30, 21));
expect(notifier.state.startTime, const TimeOfDay(hour: 17, minute: 30));
});
});
group('GymStateNotifier.clear', () {
test('Resets the workout start time', () {
// Arrange
notifier.state = notifier.state.copyWith(workoutStart: DateTime(2024, 5, 1, 10, 0));
// Act
withClock(Clock.fixed(DateTime(2024, 5, 2, 9, 15)), () {
notifier.clear();
});
// Assert
expect(notifier.state.workoutStart, DateTime(2024, 5, 2, 9, 15));
});
});
group('GymStateNotifier.initData', () {
test('Resets the workout start time when the state is reset', () {
// Arrange
notifier.state = notifier.state.copyWith(
isInitialized: false,
workoutStart: DateTime(2024, 5, 1, 10, 0),
);
// Act
withClock(Clock.fixed(DateTime(2024, 5, 2, 18, 0)), () {
notifier.initData(getTestRoutine(), 1, 1);
});
// Assert
expect(notifier.state.workoutStart, DateTime(2024, 5, 2, 18, 0));
});
test('Keeps the workout start time when the state is not reset', () {
// Arrange
notifier.state = notifier.state.copyWith(
isInitialized: true,
workoutStart: DateTime(2024, 5, 1, 10, 0),
);
// Act
notifier.initData(getTestRoutine(), 1, 1);
// Assert
expect(notifier.state.workoutStart, DateTime(2024, 5, 1, 10, 0));
});
});
group('GymModeState.copyWith', () {
test('Keeps the log scope when it is not passed', () {
final state = notifier.state.copyWith(logScopeWeeks: 8);
expect(state.copyWith(showDistinctLogs: false).logScopeWeeks, 8);
});
test('Clears the log scope on clearLogScopeWeeks', () {
final state = notifier.state.copyWith(logScopeWeeks: 8);
expect(state.copyWith(clearLogScopeWeeks: true).logScopeWeeks, isNull);
});
});
}

View File

@@ -0,0 +1,142 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:clock/clock.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:wger/features/routines/models/log.dart';
import 'package:wger/features/routines/providers/workout_logs_notifier.dart';
import 'package:wger/features/routines/providers/workout_logs_repository.dart';
import 'workout_logs_notifier_test.mocks.dart';
@GenerateMocks([WorkoutLogRepository])
void main() {
late MockWorkoutLogRepository mockRepo;
late ProviderContainer container;
setUp(() {
mockRepo = MockWorkoutLogRepository();
container = ProviderContainer.test(
overrides: [workoutLogRepositoryProvider.overrideWithValue(mockRepo)],
);
});
Log makeLog({
num repetitions = 10,
int repetitionsUnitId = 1,
num weight = 50,
int weightUnitId = 1,
DateTime? date,
}) {
return Log(
exerciseId: 1,
routineId: 100,
repetitions: repetitions,
repetitionsUnitId: repetitionsUnitId,
weight: weight,
weightUnitId: weightUnitId,
date: date ?? DateTime.utc(2026, 4, 15),
);
}
void stubLogs(List<Log> logs) {
when(
mockRepo.watchLogsByExerciseDrift(
routineId: anyNamed('routineId'),
exerciseId: anyNamed('exerciseId'),
since: anyNamed('since'),
),
).thenAnswer((_) => Stream.value(logs));
}
Future<List<Log>> readLogs({int? weeksBack, bool distinct = true}) {
final provider = pastExerciseLogsProvider(
routineId: 100,
exerciseId: 1,
weeksBack: weeksBack,
distinct: distinct,
);
// Keep the autoDispose provider alive until the stream emitted
container.listen(provider, (_, _) {});
return container.read(provider.future);
}
group('pastExerciseLogs scope', () {
test('limits the logs to the routine when no scope is set', () async {
stubLogs([]);
await readLogs();
verify(
mockRepo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1, since: null),
).called(1);
});
test('drops the routine and cuts off at the given week when a scope is set', () async {
stubLogs([]);
final now = DateTime(2026, 4, 15, 12);
await withClock(Clock.fixed(now), () => readLogs(weeksBack: 8));
verify(
mockRepo.watchLogsByExerciseDrift(
routineId: null,
exerciseId: 1,
since: now.subtract(const Duration(days: 56)),
),
).called(1);
});
});
group('pastExerciseLogs deduplication', () {
test('keeps the newest log of each repetitions/weight combination', () async {
final newest = makeLog(date: DateTime.utc(2026, 4, 16));
stubLogs([
newest,
makeLog(date: DateTime.utc(2026, 4, 15)),
makeLog(weight: 60, date: DateTime.utc(2026, 4, 14)),
]);
final logs = await readLogs();
expect(logs, hasLength(2));
expect(logs.first.date, newest.date);
expect(logs.map((l) => l.weight).toList(), [50, 60]);
});
test('keeps logs that only differ in their units', () async {
stubLogs([
makeLog(),
makeLog(repetitionsUnitId: 2),
makeLog(weightUnitId: 2),
]);
expect(await readLogs(), hasLength(3));
});
test('returns every log when disabled', () async {
stubLogs([makeLog(), makeLog(), makeLog()]);
expect(await readLogs(distinct: false), hasLength(3));
});
});
}

View File

@@ -0,0 +1,77 @@
// Mocks generated by Mockito 5.4.6 from annotations
// in wger/test/features/routines/providers/workout_logs_notifier_test.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:wger/features/routines/models/log.dart' as _i4;
import 'package:wger/features/routines/providers/workout_logs_repository.dart' as _i2;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: must_be_immutable
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
// ignore_for_file: invalid_use_of_internal_member
/// A class which mocks [WorkoutLogRepository].
///
/// See the documentation for Mockito's code generation for more information.
class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogRepository {
MockWorkoutLogRepository() {
_i1.throwOnMissingStub(this);
}
@override
_i3.Stream<List<_i4.Log>> watchLogsByExerciseDrift({
int? routineId,
required int? exerciseId,
DateTime? since,
}) =>
(super.noSuchMethod(
Invocation.method(#watchLogsByExerciseDrift, [], {
#routineId: routineId,
#exerciseId: exerciseId,
#since: since,
}),
returnValue: _i3.Stream<List<_i4.Log>>.empty(),
)
as _i3.Stream<List<_i4.Log>>);
@override
_i3.Future<void> deleteLocalDrift(String? id) =>
(super.noSuchMethod(
Invocation.method(#deleteLocalDrift, [id]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> updateLocalDrift(_i4.Log? log) =>
(super.noSuchMethod(
Invocation.method(#updateLocalDrift, [log]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
@override
_i3.Future<void> addLocalDrift(_i4.Log? log) =>
(super.noSuchMethod(
Invocation.method(#addLocalDrift, [log]),
returnValue: _i3.Future<void>.value(),
returnValueForMissingStub: _i3.Future<void>.value(),
)
as _i3.Future<void>);
}

View File

@@ -1,6 +1,6 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
* Copyright (c) 2026 - 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
@@ -39,7 +39,7 @@ void main() {
Log makeLog({
int exerciseId = 1,
int routineId = 100,
int? routineId = 100,
String? sessionId,
DateTime? date,
num weight = 50,
@@ -151,6 +151,44 @@ void main() {
expect(await readSessions(), hasLength(2));
});
test('creates a session without a routine for a log without a routine', () async {
final log = makeLog(routineId: null, date: DateTime.utc(2026, 4, 15, 18));
await repo.addLocalDrift(log);
final sessions = await readSessions();
expect(sessions, hasLength(1));
expect(sessions.single.routineId, isNull);
expect(log.sessionId, sessions.single.id);
});
test('reuses an existing session without a routine for a log without a routine', () async {
final existingSession = WorkoutSession(
id: 'free-session',
routineId: null,
date: DateTime.utc(2026, 4, 15),
);
await db.into(db.workoutSessionTable).insert(existingSession.toCompanion());
final log = makeLog(routineId: null, date: DateTime.utc(2026, 4, 15, 18));
await repo.addLocalDrift(log);
expect(await readSessions(), hasLength(1));
expect(log.sessionId, existingSession.id);
});
test('does not attach a log without a routine to a session with one', () async {
await db
.into(db.workoutSessionTable)
.insert(
WorkoutSession(routineId: 100, date: DateTime.utc(2026, 4, 15)).toCompanion(),
);
await repo.addLocalDrift(makeLog(routineId: null, date: DateTime.utc(2026, 4, 15)));
expect(await readSessions(), hasLength(2));
});
});
group('updateLocalDrift', () {
@@ -242,6 +280,86 @@ void main() {
expect(logs.single.weightUnitObj?.name, 'kg');
});
test('returns logs without a routine, e.g. free logging on the server', () async {
// The server allows logs without a routine. Such a row arrives via
// PowerSync with routine_id = NULL and must map cleanly
await seedUnits();
await db.customStatement(
'INSERT INTO manager_workoutlog (id, exercise_id, routine_id, weight, date) '
"VALUES ('free-log', 1, NULL, 50.0, '2026-04-15T10:30:00.000Z')",
);
final logs = await repo.watchLogsByExerciseDrift(exerciseId: 1).first;
expect(logs, hasLength(1));
expect(logs.single.routineId, isNull);
});
test('returns the logs of every routine when no routine is given', () async {
await seedUnits();
await db
.into(db.workoutLogTable)
.insert(makeLog(exerciseId: 1, routineId: 100).toCompanion());
await db
.into(db.workoutLogTable)
.insert(makeLog(exerciseId: 1, routineId: 999).toCompanion());
await db
.into(db.workoutLogTable)
.insert(makeLog(exerciseId: 2, routineId: 100).toCompanion());
final logs = await repo.watchLogsByExerciseDrift(exerciseId: 1).first;
expect(logs.map((l) => l.routineId).toSet(), {100, 999});
});
test('only returns logs on or after the given date', () async {
await seedUnits();
await db
.into(db.workoutLogTable)
.insert(makeLog(date: DateTime.utc(2026, 4, 14), weight: 14).toCompanion());
await db
.into(db.workoutLogTable)
.insert(makeLog(date: DateTime.utc(2026, 4, 16), weight: 16).toCompanion());
final logs = await repo
.watchLogsByExerciseDrift(
routineId: 100,
exerciseId: 1,
since: DateTime.utc(2026, 4, 15),
)
.first;
expect(logs.map((l) => l.weight).toList(), [16]);
});
test('compares a cutoff given in local time as an instant', () async {
// Dates are stored as UTC text, a local cutoff is bound with its offset
// appended. Both sides go through JULIANDAY, so the comparison happens on
// the instant rather than on the raw string.
await seedUnits();
await db
.into(db.workoutLogTable)
.insert(makeLog(date: DateTime.utc(2026, 4, 15, 9)).toCompanion());
final justBefore = await repo
.watchLogsByExerciseDrift(
routineId: 100,
exerciseId: 1,
since: DateTime.utc(2026, 4, 15, 8, 30).toLocal(),
)
.first;
expect(justBefore, hasLength(1), reason: 'Cutoff half an hour before the log');
final justAfter = await repo
.watchLogsByExerciseDrift(
routineId: 100,
exerciseId: 1,
since: DateTime.utc(2026, 4, 15, 9, 30).toLocal(),
)
.first;
expect(justAfter, isEmpty, reason: 'Cutoff half an hour after the log');
});
test('re-emits when a matching log is added', () async {
await seedUnits();
final stream = repo.watchLogsByExerciseDrift(routineId: 100, exerciseId: 1);

View File

@@ -535,13 +535,15 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i27.WorkoutLogReposi
@override
_i10.Stream<List<_i28.Log>> watchLogsByExerciseDrift({
required int? routineId,
int? routineId,
required int? exerciseId,
DateTime? since,
}) =>
(super.noSuchMethod(
Invocation.method(#watchLogsByExerciseDrift, [], {
#routineId: routineId,
#exerciseId: exerciseId,
#since: since,
}),
returnValue: _i10.Stream<List<_i28.Log>>.empty(),
)

View File

@@ -138,13 +138,15 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogReposit
@override
_i5.Stream<List<_i10.Log>> watchLogsByExerciseDrift({
required int? routineId,
int? routineId,
required int? exerciseId,
DateTime? since,
}) =>
(super.noSuchMethod(
Invocation.method(#watchLogsByExerciseDrift, [], {
#routineId: routineId,
#exerciseId: exerciseId,
#since: since,
}),
returnValue: _i5.Stream<List<_i10.Log>>.empty(),
)

View File

@@ -0,0 +1,102 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/features/routines/widgets/gym_mode/elapsed_time.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late ProviderContainer container;
setUp(() {
container = ProviderContainer(
overrides: [
gymStateProvider.overrideWith(() => GymStateNotifier()),
],
);
});
tearDown(() {
container.dispose();
});
Future<void> pumpTimer(WidgetTester tester) async {
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: const MaterialApp(
home: Scaffold(
body: ElapsedWorkoutTimer(),
),
),
),
);
}
testWidgets('Shows the time elapsed since the workout start', (tester) async {
final now = DateTime(2024, 5, 1, 12, 0, 0);
await withClock(Clock.fixed(now), () async {
final notifier = container.read(gymStateProvider.notifier);
notifier.state = GymModeState(
workoutStart: now.subtract(const Duration(minutes: 1, seconds: 5)),
);
await pumpTimer(tester);
expect(find.text('1:05'), findsOneWidget);
});
});
testWidgets('Shows zero for a workout start in the future', (tester) async {
final now = DateTime(2024, 5, 1, 12, 0, 0);
await withClock(Clock.fixed(now), () async {
final notifier = container.read(gymStateProvider.notifier);
notifier.state = GymModeState(
workoutStart: now.add(const Duration(minutes: 5)),
);
await pumpTimer(tester);
expect(find.text('0:00'), findsOneWidget);
});
});
group('ElapsedWorkoutTimer.format', () {
test('Formats durations under an hour as m:ss', () {
expect(ElapsedWorkoutTimer.format(Duration.zero), '0:00');
expect(ElapsedWorkoutTimer.format(const Duration(seconds: 9)), '0:09');
expect(ElapsedWorkoutTimer.format(const Duration(minutes: 59, seconds: 59)), '59:59');
});
test('Formats durations over an hour as h:mm:ss', () {
expect(ElapsedWorkoutTimer.format(const Duration(hours: 1)), '1:00:00');
expect(
ElapsedWorkoutTimer.format(const Duration(hours: 2, minutes: 3, seconds: 4)),
'2:03:04',
);
});
});
}

View File

@@ -42,6 +42,23 @@ import '../../../../../test_data/exercises.dart';
import '../../../../../test_data/routines.dart' as testdata;
import 'log_page_test.mocks.dart';
/// Strips the exercise off a fixture log, watchLogsByExerciseDrift only joins the units
Log asDriftLog(Log log) =>
Log(
id: log.id,
exerciseId: log.exerciseId,
iteration: log.iteration,
slotEntryId: log.slotEntryId,
routineId: log.routineId,
sessionId: log.sessionId,
repetitions: log.repetitions,
rir: log.rir,
weight: log.weight,
date: log.date,
)
..repetitionUnit = log.repetitionsUnitObj
..weightUnit = log.weightUnitObj;
@GenerateMocks([WorkoutLogRepository])
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@@ -65,7 +82,9 @@ void main() {
),
).thenAnswer((invocation) {
final exerciseId = invocation.namedArguments[#exerciseId] as int;
return Stream.value(testdata.getTestRoutine().filterLogsByExercise(exerciseId));
return Stream.value(
testdata.getTestRoutine().filterLogsByExercise(exerciseId).map(asDriftLog).toList(),
);
});
container = ProviderContainer.test(
overrides: [workoutLogRepositoryProvider.overrideWithValue(mockWorkoutLogRepo)],

View File

@@ -34,13 +34,15 @@ class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogReposit
@override
_i3.Stream<List<_i4.Log>> watchLogsByExerciseDrift({
required int? routineId,
int? routineId,
required int? exerciseId,
DateTime? since,
}) =>
(super.noSuchMethod(
Invocation.method(#watchLogsByExerciseDrift, [], {
#routineId: routineId,
#exerciseId: exerciseId,
#since: since,
}),
returnValue: _i3.Stream<List<_i4.Log>>.empty(),
)

View File

@@ -0,0 +1,74 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:wger/features/routines/providers/gym_state.dart';
import 'package:wger/features/routines/providers/gym_state_notifier.dart';
import 'package:wger/features/routines/widgets/gym_mode/elapsed_time.dart';
import 'package:wger/features/routines/widgets/gym_mode/navigation.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late ProviderContainer container;
setUp(() {
container = ProviderContainer(
overrides: [
gymStateProvider.overrideWith(() => GymStateNotifier()),
],
);
});
tearDown(() {
container.dispose();
});
Future<void> pumpFooter(WidgetTester tester) async {
final controller = PageController();
addTearDown(controller.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
home: Scaffold(
body: NavigationFooter(controller),
),
),
),
);
}
testWidgets('Shows the elapsed workout timer by default', (tester) async {
await pumpFooter(tester);
expect(find.byType(ElapsedWorkoutTimer), findsOneWidget);
});
testWidgets('Hides the elapsed workout timer when disabled', (tester) async {
final notifier = container.read(gymStateProvider.notifier);
notifier.state = GymModeState(showWorkoutDuration: false);
await pumpFooter(tester);
expect(find.byType(ElapsedWorkoutTimer), findsNothing);
});
}

View File

@@ -115,23 +115,24 @@ void main() {
notifier.state = notifier.state.copyWith(
routine: testRoutine,
startTime: const TimeOfDay(hour: 13, minute: 35),
workoutStart: DateTime(2021, 5, 1, 13, 35),
);
notifier.calculatePages();
await tester.pumpWidget(renderSessionPage());
await tester.pumpAndSettle();
await withClock(Clock.fixed(DateTime(2021, 5, 1, 15, 23)), () async {
await tester.pumpWidget(renderSessionPage());
await tester.pumpAndSettle();
final timeNow = TimeOfDay.now().format(tester.element(find.byType(TextFormField).first));
expect(find.text('1:35 PM'), findsOneWidget);
expect(find.text(timeNow), findsOneWidget);
expect(find.text('1:35 PM'), findsOneWidget);
expect(find.text('3:23 PM'), findsOneWidget);
});
});
testWidgets('Test correct default data (no existing session)', (WidgetTester tester) async {
// Arrange
testRoutine.sessions = [];
notifier.state = notifier.state.copyWith(
startTime: const TimeOfDay(hour: 13, minute: 35),
workoutStart: DateTime(2021, 5, 1, 13, 35),
);
// Act

View File

@@ -107,10 +107,17 @@ void main() {
await tester.tap(showTimerSwitch);
await tester.pump();
// Toggle show workout duration
final durationSwitch = find.byKey(const ValueKey('gym-mode-option-show-workout-duration'));
expect(durationSwitch, findsOneWidget);
await tester.tap(durationSwitch);
await tester.pump();
final notifier = container.read(gymStateProvider.notifier);
expect(notifier.state.showExercisePages, isFalse);
expect(notifier.state.showTimerPages, isFalse);
expect(notifier.state.alertOnCountdownEnd, isTrue);
expect(notifier.state.showWorkoutDuration, isFalse);
});
testWidgets('Dropdown, text field and refresh button update notifier state', (tester) async {
@@ -169,4 +176,45 @@ void main() {
expect(notifier.state.countdownDuration.inSeconds, DEFAULT_COUNTDOWN_DURATION);
});
testWidgets('Log history options update notifier state', (tester) async {
await pumpGymModeOptions(tester);
await tester.tap(find.byKey(const ValueKey('gym-mode-options-tile')));
await tester.pumpAndSettle();
final notifier = container.read(gymStateProvider.notifier);
expect(notifier.state.logScopeWeeks, isNull, reason: 'Defaults to the current routine');
expect(notifier.state.showDistinctLogs, isTrue);
// The tiles sit at the bottom of the scrollable options card
final scopeDropdown = find.byKey(const ValueKey('log-scope-dropdown'));
await tester.ensureVisible(scopeDropdown);
await tester.pumpAndSettle();
// Limit the scope to the last 12 weeks
await tester.tap(scopeDropdown);
await tester.pumpAndSettle();
await tester.tap(find.text('Last 12 weeks').last);
await tester.pumpAndSettle();
expect(notifier.state.logScopeWeeks, 12);
// And back to the current routine
await tester.ensureVisible(scopeDropdown);
await tester.pumpAndSettle();
await tester.tap(scopeDropdown);
await tester.pumpAndSettle();
await tester.tap(find.text('Current routine').last);
await tester.pumpAndSettle();
expect(notifier.state.logScopeWeeks, isNull);
final distinctSwitch = find.byKey(const ValueKey('gym-mode-distinct-logs'));
await tester.ensureVisible(distinctSwitch);
await tester.pumpAndSettle();
await tester.tap(distinctSwitch);
await tester.pump();
expect(notifier.state.showDistinctLogs, isFalse);
});
}

View File

@@ -0,0 +1,46 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:powersync/powersync.dart' show SyncStatus;
/// Builds a [SyncStatus] for tests. Since powersync 2.3.2 the constructor is
/// @internal and requires every parameter, so fabricate statuses through this
/// helper instead.
SyncStatus buildSyncStatus({
bool connected = false,
bool connecting = false,
bool downloading = false,
bool uploading = false,
DateTime? lastSyncedAt,
Object? downloadError,
Object? uploadError,
}) {
// ignore: invalid_use_of_internal_member
return SyncStatus(
connected: connected,
connecting: connecting,
downloading: downloading,
uploading: uploading,
lastSyncedAt: lastSyncedAt,
downloadProgress: null,
downloadError: downloadError,
uploadError: uploadError,
priorityStatusEntries: const [],
streamSubscriptions: null,
);
}

View File

@@ -17,9 +17,12 @@
*/
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:logging/logging.dart';
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:powersync/powersync.dart';
@@ -175,9 +178,28 @@ void main() {
});
group('fetchCredentials', () {
/// Probe client answering 200 for any liveness probe, so the endpoint
/// resolution keeps whatever URL the token response advertised.
MockClient anyLivenessOk() => MockClient(
(request) async => request.url.path.endsWith('/probes/liveness')
? http.Response('{"ready":true}', 200)
: http.Response('not found', 404),
);
/// Probe client answering 200 only for [probeUrl].
MockClient liveOnlyAt(String probeUrl) => MockClient(
(request) async => request.url.toString() == probeUrl
? http.Response('{"ready":true}', 200)
: http.Response('not found', 404),
);
test('builds PowerSyncCredentials with userId from sub and expiresAt from exp', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: anyLivenessOk(),
);
final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
@@ -194,7 +216,11 @@ void main() {
test('coerces a numeric sub into a String (Django sends ints)', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: anyLivenessOk(),
);
final jwt = makeJwt({'sub': 42, 'exp': 1700000000});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
@@ -207,7 +233,11 @@ void main() {
test('still produces credentials when JWT is opaque (userId/expiresAt null)', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: anyLivenessOk(),
);
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': 'not.a.jwt', 'powersync_url': 'https://ps.example.com'},
);
@@ -220,6 +250,92 @@ void main() {
expect(creds.expiresAt, isNull);
});
test('falls back to <baseUrl>/ps/ when powersync_url does not answer the probe', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: liveOnlyAt('http://example.invalid/ps/probes/liveness'),
);
final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'http://localhost/ps/'},
);
final creds = await connector.fetchCredentials();
expect(creds!.endpoint, 'http://example.invalid/ps/');
});
test('falls back to <baseUrl>/ps/ when powersync_url is missing', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: liveOnlyAt('http://example.invalid/ps/probes/liveness'),
);
final jwt = makeJwt({'sub': 'user-42', 'exp': 1700000000});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt},
);
final creds = await connector.fetchCredentials();
expect(creds!.endpoint, 'http://example.invalid/ps/');
});
test('probes once per powersync_url value, again when it changes', () async {
final probes = <String>[];
final mockApi = MockApiClient();
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: MockClient((request) async {
probes.add(request.url.toString());
return http.Response('{"ready":true}', 200);
}),
);
final jwt = makeJwt({'sub': 'u', 'exp': 1700000000});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
await connector.fetchCredentials();
await connector.fetchCredentials();
expect(probes, ['https://ps.example.com/probes/liveness']);
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://other.example.com'},
);
final creds = await connector.fetchCredentials();
expect(probes, hasLength(2));
expect(creds!.endpoint, 'https://other.example.com');
});
test('does not cache a failed resolution', () async {
final probes = <String>[];
final mockApi = MockApiClient();
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: MockClient((request) async {
probes.add(request.url.toString());
return http.Response('not found', 404);
}),
);
final jwt = makeJwt({'sub': 'u', 'exp': 1700000000});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
expect(await connector.fetchCredentials(), isNull);
expect(await connector.fetchCredentials(), isNull);
// Both candidates probed on both attempts: no negative caching.
expect(probes, hasLength(4));
});
test('returns null when the backend is unreachable', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(baseUrl: 'http://example.invalid', apiClient: mockApi);
@@ -229,6 +345,121 @@ void main() {
expect(await connector.fetchCredentials(), isNull);
});
test('anchors expiresAt to the local clock via the token lifetime', () async {
final mockApi = MockApiClient();
final connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: anyLivenessOk(),
);
// iat/exp lie far in the past; only their 600 s difference may matter.
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
final creds = await connector.fetchCredentials();
final expected = DateTime.now().toUtc().add(const Duration(seconds: 600));
expect(creds!.expiresAt!.difference(expected).abs(), lessThan(const Duration(seconds: 5)));
});
group('unreachable-backend logging', () {
late MockApiClient mockApi;
late DjangoConnector connector;
late List<LogRecord> records;
setUp(() {
mockApi = MockApiClient();
connector = DjangoConnector(
baseUrl: 'http://example.invalid',
apiClient: mockApi,
client: anyLivenessOk(),
);
records = [];
final sub = Logger.root.onRecord.listen(records.add);
addTearDown(sub.cancel);
});
Iterable<LogRecord> infoLines(String needle) =>
records.where((r) => r.level == Level.INFO && r.message.contains(needle));
test('logs the outage at INFO once, not per retry', () async {
when(
mockApi.getPowersyncToken(),
).thenThrow(http.ClientException('Connection refused'));
await connector.fetchCredentials();
await connector.fetchCredentials();
await connector.fetchCredentials();
expect(infoLines('backend unreachable'), hasLength(1));
});
test('logs recovery once the fetch succeeds again', () async {
when(
mockApi.getPowersyncToken(),
).thenThrow(const SocketException('Network is unreachable'));
await connector.fetchCredentials();
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
await connector.fetchCredentials();
expect(infoLines('reachable again'), hasLength(1));
});
test('a new outage after recovery is logged immediately again', () async {
when(
mockApi.getPowersyncToken(),
).thenThrow(http.ClientException('Connection refused'));
await connector.fetchCredentials();
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
await connector.fetchCredentials();
when(
mockApi.getPowersyncToken(),
).thenThrow(http.ClientException('Connection refused'));
await connector.fetchCredentials();
expect(infoLines('backend unreachable'), hasLength(2));
});
test('logs the endpoint once, again only when it changes', () async {
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
await connector.fetchCredentials();
await connector.fetchCredentials();
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://other.example.com'},
);
await connector.fetchCredentials();
expect(infoLines('endpoint https://ps.example.com'), hasLength(1));
expect(infoLines('endpoint https://other.example.com'), hasLength(1));
});
test('does not log recovery when there was no outage', () async {
final jwt = makeJwt({'sub': 'u', 'iat': 1700000000, 'exp': 1700000600});
when(mockApi.getPowersyncToken()).thenAnswer(
(_) async => {'token': jwt, 'powersync_url': 'https://ps.example.com'},
);
await connector.fetchCredentials();
expect(infoLines('reachable again'), isEmpty);
});
});
});
group('processTransaction', () {

View File

@@ -0,0 +1,142 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (c) 2026 wger Team
*
* wger Workout Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:logging/logging.dart';
import 'package:wger/powersync/sync_watchdog.dart';
import '../helpers/sync_status.dart';
void main() {
late SyncStreamWatchdog watchdog;
late List<LogRecord> records;
setUp(() {
watchdog = SyncStreamWatchdog();
records = [];
final sub = Logger.root.onRecord.listen(records.add);
addTearDown(sub.cancel);
addTearDown(watchdog.dispose);
});
Iterable<LogRecord> logLines(Level level, String needle) =>
records.where((r) => r.level == level && r.message.contains(needle));
test('flags a connection that never delivers a checkpoint', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connecting: true));
async.elapse(watchdog.timeout - const Duration(seconds: 1));
expect(watchdog.stalled.value, isFalse);
async.elapse(const Duration(seconds: 2));
expect(watchdog.stalled.value, isTrue);
expect(logLines(Level.WARNING, 'may be blocked'), hasLength(1));
});
});
test('the silent connect/EOF retry loop does not reset the timer', () {
fakeAsync((async) {
// Mimic the status flapping of an iteration that starts, ends cleanly
// and retries: connecting toggles, lastSyncedAt never moves.
for (var i = 0; i < 20; i++) {
watchdog.onStatus(buildSyncStatus(connecting: true));
async.elapse(const Duration(seconds: 5));
watchdog.onStatus(buildSyncStatus());
async.elapse(const Duration(seconds: 5));
}
expect(watchdog.stalled.value, isTrue);
expect(logLines(Level.WARNING, 'may be blocked'), hasLength(1));
});
});
test('a checkpoint disarms the watchdog, idle time does not re-trigger it', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connecting: true));
async.elapse(const Duration(seconds: 10));
watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
// A healthy connection can sit idle without new status events for far
// longer than the timeout.
async.elapse(watchdog.timeout * 3);
expect(watchdog.stalled.value, isFalse);
expect(records, isEmpty);
});
});
test('an active download holds the watchdog off', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connected: true, downloading: true));
async.elapse(watchdog.timeout * 2);
expect(watchdog.stalled.value, isFalse);
});
});
test('a surfaced sync error holds the watchdog off', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connecting: true, downloadError: Exception('boom')));
async.elapse(watchdog.timeout * 2);
expect(watchdog.stalled.value, isFalse);
});
});
test('recovers and logs once when a checkpoint finally arrives', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connecting: true));
async.elapse(watchdog.timeout);
expect(watchdog.stalled.value, isTrue);
watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
expect(watchdog.stalled.value, isFalse);
expect(logLines(Level.INFO, 'recovered'), hasLength(1));
});
});
test('reset() clears the pending timer and the stalled flag', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connecting: true));
async.elapse(watchdog.timeout);
expect(watchdog.stalled.value, isTrue);
watchdog.reset();
expect(watchdog.stalled.value, isFalse);
// No further timer fires after the reset.
async.elapse(watchdog.timeout * 2);
expect(watchdog.stalled.value, isFalse);
});
});
test('re-arms after reset() for the next connection epoch', () {
fakeAsync((async) {
watchdog.onStatus(buildSyncStatus(connected: true, lastSyncedAt: DateTime(2026, 7, 23)));
watchdog.reset();
watchdog.onStatus(buildSyncStatus(connecting: true));
async.elapse(watchdog.timeout);
expect(watchdog.stalled.value, isTrue);
});
});
}