Merge branch 'master' into refactor_login_page

This commit is contained in:
Roland Geider
2022-10-14 21:11:00 +02:00
committed by GitHub
171 changed files with 6732 additions and 938 deletions

View File

@@ -78,7 +78,7 @@ jobs:
WGER_API_KEY: ${{ secrets.WGER_API_KEY }}
- name: Upload build to Play Store
uses: maierj/fastlane-action@v2.1.0
uses: maierj/fastlane-action@v2.2.1
with:
lane: production

View File

@@ -1,12 +1,11 @@
name: Continous Integration
on:
push:
branches: [ master ]
paths:
- '**.dart'
- 'pubspec.yaml'
pull_request:
branches: [ master ]
branches: [ pull_request, master ]
paths:
- '**.dart'
- 'pubspec.yaml'

View File

@@ -20,7 +20,7 @@ jobs:
uses: subosito/flutter-action@v1
with:
channel: 'stable'
flutter-version: '3.0.x'
flutter-version: '3.3.x'
- name: Get dependencies
run: flutter pub get

5
.gitignore vendored
View File

@@ -48,3 +48,8 @@ app.*.map.json
/fastlane/metadata/envfiles/wger.properties
/fastlane/metadata/envfiles/keys.jks
/fastlane/metadata/envfiles/key.properties
# Others
/vendor/bundle/ruby/
/coverage/

View File

@@ -16,6 +16,7 @@
- Nenza Nurfirmansyah - <https://github.com/nenzan>
- Florian Schmitz - <https://github.com/floodoo>
- Aman Negi - <https://github.com/AmanNegi>
- Sandi Milohanic - <https://github.com/sandimilohanic>
## Translators
@@ -58,3 +59,7 @@
- Bahasa Indonesia
- Nenza Nurfirmansyah <nnurfirmansyah@gmail.com> (73)
- Croatian
- Sandi Milohaic <sandi.milohanic@gmail.com>

5
Gemfile Normal file
View File

@@ -0,0 +1,5 @@
source "https://rubygems.org"
gem "fastlane"
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
eval_gemfile(plugins_path) if File.exist?(plugins_path)

221
Gemfile.lock Normal file
View File

@@ -0,0 +1,221 @@
GEM
remote: https://rubygems.org/
specs:
CFPropertyList (3.0.5)
rexml
addressable (2.8.1)
public_suffix (>= 2.0.2, < 6.0)
artifactory (3.0.15)
atomos (0.1.3)
aws-eventstream (1.2.0)
aws-partitions (1.644.0)
aws-sdk-core (3.159.0)
aws-eventstream (~> 1, >= 1.0.2)
aws-partitions (~> 1, >= 1.525.0)
aws-sigv4 (~> 1.1)
jmespath (~> 1, >= 1.6.1)
aws-sdk-kms (1.58.0)
aws-sdk-core (~> 3, >= 3.127.0)
aws-sigv4 (~> 1.1)
aws-sdk-s3 (1.114.0)
aws-sdk-core (~> 3, >= 3.127.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.4)
aws-sigv4 (1.5.2)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
claide (1.1.0)
colored (1.2)
colored2 (3.1.2)
commander (4.6.0)
highline (~> 2.0.0)
declarative (0.0.20)
digest-crc (0.6.4)
rake (>= 12.0.0, < 14.0.0)
domain_name (0.5.20190701)
unf (>= 0.0.5, < 1.0.0)
dotenv (2.8.1)
emoji_regex (3.2.3)
excon (0.93.0)
faraday (1.10.2)
faraday-em_http (~> 1.0)
faraday-em_synchrony (~> 1.0)
faraday-excon (~> 1.1)
faraday-httpclient (~> 1.0)
faraday-multipart (~> 1.0)
faraday-net_http (~> 1.0)
faraday-net_http_persistent (~> 1.0)
faraday-patron (~> 1.0)
faraday-rack (~> 1.0)
faraday-retry (~> 1.0)
ruby2_keywords (>= 0.0.4)
faraday-cookie_jar (0.0.7)
faraday (>= 0.8.0)
http-cookie (~> 1.0.0)
faraday-em_http (1.0.0)
faraday-em_synchrony (1.0.0)
faraday-excon (1.1.0)
faraday-httpclient (1.0.1)
faraday-multipart (1.0.4)
multipart-post (~> 2)
faraday-net_http (1.0.1)
faraday-net_http_persistent (1.2.0)
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
faraday_middleware (1.2.0)
faraday (~> 1.0)
fastimage (2.2.6)
fastlane (2.210.1)
CFPropertyList (>= 2.3, < 4.0.0)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
babosa (>= 1.0.3, < 2.0.0)
bundler (>= 1.12.0, < 3.0.0)
colored
commander (~> 4.6)
dotenv (>= 2.1.1, < 3.0.0)
emoji_regex (>= 0.1, < 4.0)
excon (>= 0.71.0, < 1.0.0)
faraday (~> 1.0)
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (~> 2.0.0)
naturally (~> 2.2)
optparse (~> 0.1.1)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.3)
simctl (~> 1.6.3)
terminal-notifier (>= 2.0.0, < 3.0.0)
terminal-table (>= 1.4.5, < 2.0.0)
tty-screen (>= 0.6.3, < 1.0.0)
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-travis-formatter (>= 0.0.3)
fastlane-plugin-versioning (0.5.1)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.29.0)
google-apis-core (>= 0.9.0, < 2.a)
google-apis-core (0.9.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
mini_mime (~> 1.0)
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
webrick
google-apis-iamcredentials_v1 (0.15.0)
google-apis-core (>= 0.9.0, < 2.a)
google-apis-playcustomapp_v1 (0.11.0)
google-apis-core (>= 0.9.0, < 2.a)
google-apis-storage_v1 (0.19.0)
google-apis-core (>= 0.9.0, < 2.a)
google-cloud-core (1.6.0)
google-cloud-env (~> 1.0)
google-cloud-errors (~> 1.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-errors (1.3.0)
google-cloud-storage (1.43.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.19.0)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
mini_mime (~> 1.0)
googleauth (1.2.0)
faraday (>= 0.17.3, < 3.a)
jwt (>= 1.4, < 3.0)
memoist (~> 0.16)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
signet (>= 0.16, < 2.a)
highline (2.0.3)
http-cookie (1.0.5)
domain_name (~> 0.5)
httpclient (2.8.3)
jmespath (1.6.1)
json (2.6.2)
jwt (2.5.0)
memoist (0.16.2)
mini_magick (4.11.0)
mini_mime (1.1.2)
multi_json (1.15.0)
multipart-post (2.0.0)
nanaimo (0.3.0)
naturally (2.2.1)
optparse (0.1.1)
os (1.1.4)
plist (3.6.0)
public_suffix (5.0.0)
rake (13.0.6)
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.2.5)
rouge (2.0.7)
ruby2_keywords (0.0.5)
rubyzip (2.3.2)
security (0.1.3)
signet (0.17.0)
addressable (~> 2.8)
faraday (>= 0.17.5, < 3.a)
jwt (>= 1.5, < 3.0)
multi_json (~> 1.10)
simctl (1.6.8)
CFPropertyList
naturally
terminal-notifier (2.0.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
trailblazer-option (0.1.2)
tty-cursor (0.7.1)
tty-screen (0.8.1)
tty-spinner (0.9.3)
tty-cursor (~> 0.7)
uber (0.1.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.8.2)
unicode-display_width (1.8.0)
webrick (1.7.0)
word_wrap (1.0.0)
xcodeproj (1.22.0)
CFPropertyList (>= 2.3.3, < 4.0)
atomos (~> 0.1.3)
claide (>= 1.0.2, < 2.0)
colored2 (~> 3.1)
nanaimo (~> 0.3.0)
rexml (~> 3.2.4)
xcpretty (0.3.0)
rouge (~> 2.0.7)
xcpretty-travis-formatter (1.0.1)
xcpretty (~> 0.2, >= 0.0.7)
PLATFORMS
arm64-darwin-21
x86_64-linux
DEPENDENCIES
fastlane
fastlane-plugin-versioning
BUNDLED WITH
2.2.32

View File

@@ -55,7 +55,7 @@ if(wgerApiKey == null){
}
android {
compileSdkVersion 31
compileSdkVersion 32
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
@@ -69,7 +69,7 @@ android {
// Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "de.wger.flutter"
minSdkVersion 21
targetSdkVersion 31
targetSdkVersion 32
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
manifestPlaceholders += [WGER_API_KEY: wgerApiKey]

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 314 KiB

After

Width:  |  Height:  |  Size: 312 KiB

View File

@@ -10,8 +10,9 @@ If we use a new version, update the version used by
## 2. Dry-run release before uploading
* Increase build nr in pubspec.yaml
* Increase build nr in pubspec.yaml (revert after the dry-run was successful)
* `flutter build appbundle --release`
* `bundle install`
* `bundle exec fastlane android test_configuration` (needs the different keys available)
It might be necessary to repeat these steps if upload_to_play_store returns any errors

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 MiB

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

View File

@@ -0,0 +1,10 @@
Start emulator and run
`flutter drive --driver=test_driver/screenshot_driver.dart --target=integration_test/app_test.dart`
This will generate some screenshots and save them to the Play Store metadata folder
See
* <https://github.com/openfoodfacts/smooth-app/issues/217#issuecomment-1092678779>
* <https://dev.to/mjablecnik/take-screenshot-during-flutter-integration-tests-435k>

View File

@@ -0,0 +1,67 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'gym_mode.dart';
import 'nutritional_plan.dart';
import 'weight.dart';
Future<void> takeScreenshot(tester, binding, String language, String name) async {
if (Platform.isAndroid) {
await binding.convertFlutterSurfaceToImage();
await tester.pumpAndSettle();
}
await binding
.takeScreenshot('fastlane/metadata/android/$language/images/phoneScreenshots/$name.png');
}
// Available languages in weblate for the android metadata
const languages = [
'ca',
'de-DE',
'en-US',
'es-ES',
'fr-FR',
'hi-IN',
'hr',
'it-IT',
'pt-BR',
'nb-NO',
'pl-PL',
'ru-RU',
'tr-TR',
'uk',
'zh-CN'
];
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
group('Generate screenshots', () {
for (final language in languages) {
final languageCode = language.split('-')[0];
testWidgets('gym mode screen - $language', (WidgetTester tester) async {
await tester.pumpWidget(createGymModeScreen(locale: languageCode));
await tester.tap(find.byType(TextButton));
await tester.pumpAndSettle();
await takeScreenshot(tester, binding, language, '03 - gym mode');
});
testWidgets('nutritional plan detail - $language', (WidgetTester tester) async {
await tester.pumpWidget(createNutritionalPlanScreen(locale: languageCode));
await tester.tap(find.byType(TextButton));
await tester.pumpAndSettle();
await takeScreenshot(tester, binding, language, '04 - nutritional plan');
});
testWidgets('body weight screen - $language', (WidgetTester tester) async {
await tester.pumpWidget(createWeightScreen(locale: languageCode));
await tester.pumpAndSettle();
await takeScreenshot(tester, binding, language, '05 - weight');
});
}
});
}

View File

@@ -0,0 +1,246 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:mockito/mockito.dart';
import 'package:provider/provider.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/workouts/day.dart';
import 'package:wger/models/workouts/set.dart';
import 'package:wger/models/workouts/setting.dart';
import 'package:wger/models/workouts/workout_plan.dart';
import 'package:wger/providers/exercises.dart';
import 'package:wger/providers/workout_plans.dart';
import 'package:wger/screens/gym_mode.dart';
import 'package:wger/screens/workout_plan_screen.dart';
import 'package:wger/theme/theme.dart';
import '../test/other/base_provider_test.mocks.dart';
import '../test/utils.dart';
import '../test/workout/gym_mode_screen_test.mocks.dart';
import '../test_data/exercises.dart';
import '../test_data/workouts.dart';
Widget createGymModeScreen({locale = 'en'}) {
final key = GlobalKey<NavigatorState>();
final client = MockClient();
final bases = getTestExerciseBases();
final squats = bases[0];
final squatsEn = Exercise(
id: 1,
uuid: 'uuid',
creationDate: DateTime(2021, 1, 15),
name: 'Squats',
description: 'add clever text',
baseId: tBase1.id,
language: tLanguage1,
);
squats.exercises = [squatsEn];
final benchPress = bases[1];
final benchPressEn = Exercise(
id: 1,
uuid: 'uuid',
creationDate: DateTime(2021, 1, 15),
name: 'Bench press',
description: 'add clever text',
baseId: tBase1.id,
language: tLanguage1,
);
benchPress.exercises = [benchPressEn];
final deadLift = bases[2];
final deadLiftEn = Exercise(
id: 1,
uuid: 'uuid',
creationDate: DateTime(2021, 1, 15),
name: 'Dead Lift',
description: 'add clever text',
baseId: tBase1.id,
language: tLanguage1,
);
deadLift.exercises = [deadLiftEn];
final crunches = bases[3];
final crunchesEn = Exercise(
id: 1,
uuid: 'uuid',
creationDate: DateTime(2021, 1, 15),
name: 'Crunches',
description: 'add clever text',
baseId: tBase1.id,
language: tLanguage1,
);
crunches.exercises = [crunchesEn];
final mockExerciseProvider = MockExercisesProvider();
when(mockExerciseProvider.findExerciseBaseById(1)).thenReturn(squats);
when(mockExerciseProvider.findExerciseBaseById(2)).thenReturn(benchPress);
when(mockExerciseProvider.findExerciseBaseById(3)).thenReturn(crunches);
final setting1 = Setting(
setId: 1,
order: 1,
exerciseBaseId: 1,
repetitionUnitId: 1,
reps: 5,
weightUnitId: 1,
comment: 'ddd',
rir: '2',
);
setting1.repetitionUnit = repetitionUnit1;
setting1.weightUnit = weightUnit1;
setting1.exerciseBase = squats;
setting1.weight = 100;
final setting2 = Setting(
setId: 1,
order: 1,
exerciseBaseId: 2,
repetitionUnitId: 1,
reps: 6,
weightUnitId: 1,
comment: 'ddd',
rir: '1.5',
);
setting2.repetitionUnit = repetitionUnit1;
setting2.weightUnit = weightUnit1;
setting2.exerciseBase = benchPress;
setting2.weight = 80;
final setting2b = Setting(
setId: 1,
order: 1,
exerciseBaseId: 2,
repetitionUnitId: 1,
reps: 8,
weightUnitId: 1,
comment: 'ddd',
rir: '2',
);
setting2b.repetitionUnit = repetitionUnit1;
setting2b.weightUnit = weightUnit1;
setting2b.exerciseBase = benchPress;
setting2b.weight = 60;
final setting3 = Setting(
setId: 1,
order: 1,
exerciseBaseId: 2,
repetitionUnitId: 1,
reps: 20,
weightUnitId: 1,
comment: '',
rir: null,
);
setting3.repetitionUnit = repetitionUnit1;
setting3.weightUnit = weightUnit1;
setting3.exerciseBase = crunches;
final setting4 = Setting(
setId: 1,
order: 1,
exerciseBaseId: 2,
repetitionUnitId: 1,
reps: 8,
weightUnitId: 1,
comment: '',
rir: null,
);
setting4.repetitionUnit = repetitionUnit1;
setting4.weightUnit = weightUnit1;
setting4.exerciseBase = deadLift;
setting4.weight = 120;
final set1 = Set.withData(
id: 1,
day: 1,
sets: 3,
order: 1,
);
set1.addExerciseBase(squats);
set1.settings.add(setting1);
set1.settings.add(setting1);
set1.settings.add(setting1);
set1.settings.add(setting1);
final set2 = Set.withData(
id: 2,
day: 1,
sets: 3,
order: 1,
);
set2.addExerciseBase(benchPress);
set2.settings.add(setting2);
set2.settings.add(setting2);
set2.settings.add(setting2b);
set2.settings.add(setting2b);
final set3 = Set.withData(
id: 3,
day: 1,
sets: 3,
order: 1,
);
set3.addExerciseBase(crunches);
set3.settings.add(setting3);
final set4 = Set.withData(
id: 4,
day: 1,
sets: 3,
order: 1,
);
set4.addExerciseBase(deadLift);
set4.settings.add(setting4);
set4.settings.add(setting4);
set4.settings.add(setting4);
set4.settings.add(setting4);
final day1 = Day()
..id = 1
..workoutId = 1
..description = 'test day 1'
..daysOfWeek = [1, 2];
day1.sets.add(set1);
day1.sets.add(set2);
day1.sets.add(set4);
day1.sets.add(set3);
final workout = WorkoutPlan(
id: 1,
creationDate: DateTime(2021, 01, 01),
name: 'test workout 1',
days: [day1],
);
return ChangeNotifierProvider<WorkoutPlansProvider>(
create: (context) => WorkoutPlansProvider(
testAuthProvider,
mockExerciseProvider,
[workout],
client,
),
child: ChangeNotifierProvider<ExercisesProvider>(
create: (context) => mockExerciseProvider,
child: MaterialApp(
locale: Locale(locale),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
navigatorKey: key,
theme: wgerTheme,
home: TextButton(
onPressed: () => key.currentState!.push(
MaterialPageRoute<void>(
settings: RouteSettings(arguments: workout.days.first),
builder: (_) => GymModeScreen(),
),
),
child: const SizedBox(),
),
routes: {
WorkoutPlanScreen.routeName: (ctx) => WorkoutPlanScreen(),
},
),
),
);
}

View File

@@ -0,0 +1,122 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:wger/models/nutrition/ingredient.dart';
import 'package:wger/models/nutrition/log.dart';
import 'package:wger/models/nutrition/meal.dart';
import 'package:wger/models/nutrition/meal_item.dart';
import 'package:wger/models/nutrition/nutritional_plan.dart';
import 'package:wger/providers/body_weight.dart';
import 'package:wger/providers/nutrition.dart';
import 'package:wger/screens/nutritional_plan_screen.dart';
import 'package:wger/theme/theme.dart';
import '../test/other/base_provider_test.mocks.dart';
import '../test/utils.dart';
Widget createNutritionalPlanScreen({locale = 'en'}) {
final key = GlobalKey<NavigatorState>();
final client = MockClient();
final muesli = Ingredient(
id: 1,
code: '123456787',
name: 'Müsli',
creationDate: DateTime(2021, 5, 1),
energy: 500,
carbohydrates: 10,
carbohydratesSugar: 2,
protein: 5,
fat: 20,
fatSaturated: 7,
fibres: 12,
sodium: 0.5,
);
final milk = Ingredient(
id: 1,
code: '123456787',
name: 'Milk',
creationDate: DateTime(2021, 5, 1),
energy: 500,
carbohydrates: 10,
carbohydratesSugar: 2,
protein: 5,
fat: 20,
fatSaturated: 7,
fibres: 12,
sodium: 0.5,
);
final apple = Ingredient(
id: 1,
code: '123456787',
name: 'Apple',
creationDate: DateTime(2021, 5, 1),
energy: 500,
carbohydrates: 10,
carbohydratesSugar: 2,
protein: 5,
fat: 20,
fatSaturated: 7,
fibres: 12,
sodium: 0.5,
);
final mealItem1 = MealItem(ingredientId: 1, amount: 100, ingredient: muesli);
final mealItem2 = MealItem(ingredientId: 2, amount: 75, ingredient: milk);
final mealItem3 = MealItem(ingredientId: 3, amount: 100, ingredient: apple);
final meal1 = Meal(
id: 1,
plan: 1,
time: const TimeOfDay(hour: 8, minute: 30),
name: 'Breakfast',
mealItems: [mealItem1, mealItem2],
);
final meal2 = Meal(
id: 2,
plan: 1,
time: const TimeOfDay(hour: 11, minute: 0),
name: 'Snack 1',
mealItems: [mealItem3],
);
final NutritionalPlan plan = NutritionalPlan(
id: 1,
description: 'Mini diet',
creationDate: DateTime(2021, 5, 23),
meals: [meal1, meal2],
);
// Add logs
plan.logs.add(Log.fromMealItem(mealItem1, 1, 1, DateTime(2021, 6, 1)));
plan.logs.add(Log.fromMealItem(mealItem2, 1, 1, DateTime(2021, 6, 1)));
plan.logs.add(Log.fromMealItem(mealItem3, 1, 1, DateTime(2021, 6, 10)));
return MultiProvider(
providers: [
ChangeNotifierProvider<NutritionPlansProvider>(
create: (context) => NutritionPlansProvider(testAuthProvider, [], client),
),
ChangeNotifierProvider<BodyWeightProvider>(
create: (context) => BodyWeightProvider(testAuthProvider, [], client),
),
],
child: MaterialApp(
locale: Locale(locale),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: wgerTheme,
navigatorKey: key,
home: TextButton(
onPressed: () => key.currentState!.push(
MaterialPageRoute<void>(
settings: RouteSettings(arguments: plan),
builder: (_) => NutritionalPlanScreen(),
),
),
child: const SizedBox(),
),
),
);
}

View File

@@ -0,0 +1,47 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:wger/models/body_weight/weight_entry.dart';
import 'package:wger/providers/body_weight.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/screens/weight_screen.dart';
import 'package:wger/theme/theme.dart';
import '../test/other/base_provider_test.mocks.dart';
import '../test/utils.dart';
Widget createWeightScreen({locale = 'en'}) {
return ChangeNotifierProvider<BodyWeightProvider>(
create: (context) => BodyWeightProvider(
testAuthProvider,
[
WeightEntry(id: 1, weight: 86, date: DateTime(2021, 01, 01)),
WeightEntry(id: 2, weight: 81, date: DateTime(2021, 01, 10)),
WeightEntry(id: 3, weight: 82, date: DateTime(2021, 01, 20)),
WeightEntry(id: 4, weight: 83, date: DateTime(2021, 01, 30)),
WeightEntry(id: 5, weight: 86, date: DateTime(2021, 02, 20)),
WeightEntry(id: 6, weight: 90, date: DateTime(2021, 02, 28)),
WeightEntry(id: 7, weight: 91, date: DateTime(2021, 03, 20)),
WeightEntry(id: 8, weight: 91.1, date: DateTime(2021, 03, 30)),
WeightEntry(id: 9, weight: 90, date: DateTime(2021, 05, 1)),
WeightEntry(id: 10, weight: 91, date: DateTime(2021, 6, 5)),
WeightEntry(id: 11, weight: 89, date: DateTime(2021, 6, 20)),
WeightEntry(id: 12, weight: 88, date: DateTime(2021, 7, 15)),
WeightEntry(id: 13, weight: 86, date: DateTime(2021, 7, 20)),
WeightEntry(id: 14, weight: 83, date: DateTime(2021, 7, 30)),
WeightEntry(id: 15, weight: 80, date: DateTime(2021, 8, 10))
],
MockClient(),
),
child: MaterialApp(
locale: Locale(locale),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: wgerTheme,
home: WeightScreen(),
routes: {
FormScreen.routeName: (ctx) => FormScreen(),
},
),
);
}

View File

@@ -16,7 +16,7 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
/// Size for the "smaller" icons, e.g. when they belong to less important items
@@ -45,9 +45,10 @@ const DAYS_TO_CACHE = 20;
/// Name of the submit button in forms
const SUBMIT_BUTTON_KEY_NAME = 'submit-button';
/// Local Preferences key for exercises
/// Local Preferences keys
const PREFS_EXERCISES = 'exerciseData';
const PREFS_EXERCISE_CACHE_VERSION = 'cacheVersion';
const PREFS_INGREDIENTS = 'ingredientData';
const DEFAULT_ANIMATION_DURATION = Duration(milliseconds: 200);
const DEFAULT_ANIMATION_CURVE = Curves.bounceIn;
@@ -75,3 +76,22 @@ const ENERGY_CARBOHYDRATES = 4;
/// kcal per gram of fat (approx)
const ENERGY_FAT = 9;
/// Language ID for English (fallback)
const LANGUAGE_SHORT_ENGLISH = 'en';
/// IDs of the different image art styles
///
/// Values taken from exercises/models/image.py
enum EXERCISE_IMAGE_ART_STYLE {
_, // 0 is not used
LINE_ART,
THREE_D,
LOW_POLY,
PHOTO,
OTHER,
}
/// Colors used for muscles
const COLOR_MAIN_MUSCLES = Colors.red;
const COLOR_SECONDARY_MUSCLES = Colors.orange;

View File

@@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
/// The amount of characters an exercise description needs to have
const MIN_CHARS_DESCRIPTION = 40;
/// The amount of characters an exercise name needs to have
const MIN_CHARS_NAME = 5;
const MAX_CHARS_NAME = 40;
String? validateName(String? name, BuildContext context) {
if (name!.isEmpty) {
return AppLocalizations.of(context).enterValue;
}
if (name.length < MIN_CHARS_NAME || name.length > MAX_CHARS_NAME) {
return AppLocalizations.of(context).enterCharacters(MIN_CHARS_NAME, MAX_CHARS_NAME);
}
return null;
}
String? validateDescription(String? name, BuildContext context) {
if (name!.isEmpty) {
return AppLocalizations.of(context).enterValue;
}
if (name.length < MIN_CHARS_DESCRIPTION) {
return AppLocalizations.of(context).enterMinCharacters(MIN_CHARS_DESCRIPTION);
}
return null;
}

105
lib/helpers/i18n.dart Normal file
View File

@@ -0,0 +1,105 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
/// This code is autogenerated in the backend repo in extract-i18n.py do not edit!
/// Translate dynamic strings that are returned from the server
/// These strings such as categories or equipment are returned by the server
/// in English and need to be translated here in the application (there are
/// probably better ways to do this, but that's the way it is right now).
String getTranslation(String value, BuildContext context) {
switch (value) {
case 'Lower back':
return AppLocalizations.of(context).lower_back;
case 'Seconds':
return AppLocalizations.of(context).seconds;
case 'Repetitions':
return AppLocalizations.of(context).repetitions;
case 'Dumbbell':
return AppLocalizations.of(context).dumbbell;
case 'Abs':
return AppLocalizations.of(context).abs;
case 'SZ-Bar':
return AppLocalizations.of(context).sz_bar;
case 'Miles':
return AppLocalizations.of(context).miles;
case 'Kilometers':
return AppLocalizations.of(context).kilometers;
case 'Shoulders':
return AppLocalizations.of(context).shoulders;
case 'Triceps':
return AppLocalizations.of(context).triceps;
case 'Quads':
return AppLocalizations.of(context).quads;
case 'none (bodyweight exercise)':
return AppLocalizations.of(context).none__bodyweight_exercise_;
case 'Barbell':
return AppLocalizations.of(context).barbell;
case 'Lats':
return AppLocalizations.of(context).lats;
case 'Until Failure':
return AppLocalizations.of(context).until_failure;
case 'Gym mat':
return AppLocalizations.of(context).gym_mat;
case 'Glutes':
return AppLocalizations.of(context).glutes;
case 'Bench':
return AppLocalizations.of(context).bench;
case 'Pull-up bar':
return AppLocalizations.of(context).pull_up_bar;
case 'Calves':
return AppLocalizations.of(context).calves;
case 'Arms':
return AppLocalizations.of(context).arms;
case 'Biceps':
return AppLocalizations.of(context).biceps;
case 'Kettlebell':
return AppLocalizations.of(context).kettlebell;
case 'Back':
return AppLocalizations.of(context).back;
case 'Chest':
return AppLocalizations.of(context).chest;
case 'Swiss Ball':
return AppLocalizations.of(context).swiss_ball;
case 'Minutes':
return AppLocalizations.of(context).minutes;
case 'Incline bench':
return AppLocalizations.of(context).incline_bench;
case 'Hamstrings':
return AppLocalizations.of(context).hamstrings;
case 'Legs':
return AppLocalizations.of(context).legs;
default:
return 'NOT TRANSLATED';
}
}

1
lib/l10n/app_ar.arb Normal file
View File

@@ -0,0 +1 @@
{}

View File

@@ -573,5 +573,13 @@
"scanBarcode": "Strichcode scannen",
"@scanBarcode": {
"description": "Label for scan barcode button"
}
},
"abs": "Bauch",
"arms": "Arme",
"back": "Rücken",
"calves": "Waden",
"chest": "Brust",
"legs": "Beine",
"shoulders": "Schultern",
"barbell": "Langhantel"
}

View File

@@ -1,5 +1,6 @@
{
"@@last_modified": "2020-11-11T15:04:05.523531",
"userProfile": "Your profile",
"login": "Log in",
"@login": {
"description": "Text for login button"
@@ -56,7 +57,7 @@
"@customServerUrl": {
"description": "Label in the form where the users can enter their own wger instance"
},
"customServerHint": "Enter the the address of your own server, otherwise the default one will be used",
"customServerHint": "Enter the address of your own server, otherwise the default one will be used",
"@customServerHint": {
"description": "Hint text for the form where the users can enter their own wger instance"
},
@@ -100,10 +101,19 @@
"@successfullySaved": {
"description": "Message when an item was successfully saved"
},
"exerciseList": "Exercise list",
"exercise": "Exercise",
"@exercise": {
"description": "An exercise for a workout"
},
"exercises": "Exercises",
"@exercises": {
"description": "Multiple exercises for a workout"
},
"exerciseName": "Exercise Name",
"@exerciseName": {
"description": "Label for the name of a workout exercise"
},
"searchExercise": "Search exercise to add",
"@searchExercise": {
"description": "Label on set form. Selected exercises are added to the set"
@@ -136,10 +146,6 @@
"@noWorkoutPlans": {
"description": "Message shown when the user has no workout plans"
},
"repetitions": "Repetitions",
"@repetitions": {
"description": "Repetitions for an exercise set"
},
"reps": "Reps",
"@reps": {
"description": "Shorthand for repetitions, used when space constraints are tighter"
@@ -265,12 +271,15 @@
"description": "The weight of a workout log or body weight entry"
},
"measurement": "Measurement",
"@measurement": {},
"measurements": "Measurements",
"@measurements": {
"description": "Categories for the measurements such as biceps size, body fat, etc."
},
"measurementCategoriesHelpText": "Measurement category, such as 'biceps' or 'body fat'",
"@measurementCategoriesHelpText": {},
"measurementEntriesHelpText": "The unit used to measure the category such as 'cm' or '%'",
"@measurementEntriesHelpText": {},
"date": "Date",
"@date": {
"description": "The date of a workout log or body weight entry"
@@ -296,6 +305,7 @@
"description": "The end time of a workout"
},
"timeStartAhead": "Start time cannot be ahead of end time",
"@timeStartAhead": {},
"ingredient": "Ingredient",
"@ingredient": {},
"energy": "Energy",
@@ -311,6 +321,7 @@
"description": "Energy in a meal in kilocalories, kcal"
},
"macronutrients": "Macronutrients",
"@macronutrients": {},
"planned": "Planned",
"@planned": {
"description": "Header for the column of 'planned' nutritional values, i.e. what should be eaten"
@@ -324,7 +335,9 @@
"description": "Header for the column of '7 day average' nutritional values, i.e. what was logged last week"
},
"difference": "Difference",
"@difference": {},
"percentEnergy": "Percent of energy",
"@percentEnergy": {},
"gPerBodyKg": "g per body kg",
"@gPerBodyKg": {
"description": "Label used for total sums of e.g. calories or similar in grams per Kg of body weight"
@@ -345,13 +358,13 @@
"@protein": {},
"proteinShort": "P",
"@proteinShort": {
"description" : "The first letter or short name of the word 'Protein', used in overviews"
"description": "The first letter or short name of the word 'Protein', used in overviews"
},
"carbohydrates": "Carbohydrates",
"@carbohydrates": {},
"carbohydratesShort": "C",
"@carbohydratesShort": {
"description" : "The first letter or short name of the word 'Carbohydrates', used in overviews"
"description": "The first letter or short name of the word 'Carbohydrates', used in overviews"
},
"sugars": "Sugars",
"@sugars": {},
@@ -359,7 +372,7 @@
"@fat": {},
"fatShort": "F",
"@fatShort": {
"description" : "The first letter or short name of the word 'Fat', used in overviews"
"description": "The first letter or short name of the word 'Fat', used in overviews"
},
"saturatedFat": "Saturated fat",
"@saturatedFat": {},
@@ -383,6 +396,14 @@
"@noWeightEntries": {
"description": "Message shown when the user has no logged weight entries"
},
"noMeasurementEntries": "You have no measurement entries",
"@noMeasurementntries": {
"description": "Message shown when the user has no logged measurement entries"
},
"moreMeasurementEntries": "Add new measurement",
"@moreMeasurementEntries": {
"description": "Message shown when the user wants to add new measurement"
},
"edit": "Edit",
"@edit": {},
"loadingText": "Loading...",
@@ -406,6 +427,7 @@
"description": "Switch to toggle detail / overview"
},
"goToDetailPage": "Go to detail page",
"@goToDetailPage": {},
"aboutDescription": "Thank you for using wger! wger is a collaborative open source project, made by fitness enthusiasts from around the world.",
"@aboutDescription": {
"description": "Text in the about dialog"
@@ -456,6 +478,7 @@
"@enterValue": {
"description": "Error message when the user hasn't entered a value on a required field"
},
"selectEntry": "Please select an entry",
"selectExercise": "Please select an exercise",
"@selectExercise": {
"description": "Error message when the user hasn't selected an exercise in the form"
@@ -469,6 +492,15 @@
"max": {}
}
},
"enterMinCharacters": "Please enter at least {min} characters",
"@enterMinCharacters": {
"description": "Error message when the user hasn't entered the minimum amount characters in a form",
"type": "text",
"placeholders": {
"min": {}
}
},
"baseNameEnglish": "All exercises need a base name in English",
"nrOfSets": "Sets per exercise: {nrOfSets}",
"@nrOfSets": {
"description": "Label shown on the slider where the user selects the nr of sets",
@@ -503,21 +535,25 @@
"description": "Label for the popup with general app options"
},
"takePicture": "Take a picture",
"@takePicture": {},
"chooseFromLibrary": "Choose from photo library",
"@chooseFromLibrary": {},
"gallery": "Gallery",
"@gallery": {},
"addImage": "Add image",
"@addImage": {},
"dataCopied": "Data copied to new entry",
"@dataCopied": {
"description": "Snackbar message to show on copying data to a new log entry"
},
"appUpdateTitle" : "Update needed",
"appUpdateContent" : "This version of the app is not compatible with the server, please update your application.",
"appUpdateTitle": "Update needed",
"@appUpdateTitle": {},
"appUpdateContent": "This version of the app is not compatible with the server, please update your application.",
"@appUpdateContent": {},
"productFound": "Product found",
"@productFound": {
"description": "Header label for dialog when product is found with barcode"
},
"productFoundDescription": "The barcode corresponds to this product: {productName}. Do you want to continue?",
"@productFoundDescription": {
"description": "Dialog info when product is found with barcode",
@@ -545,5 +581,71 @@
"close": "Close",
"@close": {
"description": "Translation for close"
}
},
"add_exercise_image_license": "Images must be compatible with the CC BY SA license. If in doubt, upload only photos you've taken yourself.",
"variations": "Variations",
"@variations": {
"description": "Variations of one exercise (e.g. benchpress and benchpress narrow)"
},
"alsoKnownAs": "Also known as: {aliases}",
"@alsoKnownAs": {
"placeholders": {
"aliases": {}
},
"description": "List of alternative names for an exercise"
},
"verifiedEmail": "Verified email",
"unVerifiedEmail": "Unverified email",
"verifiedEmailReason": "You need to verify your email to contribute exercises",
"verifiedEmailInfo": "A verification email was sent to {email}",
"@verifiedEmailInfo": {
"placeholders": {
"email": {}
}
},
"alternativeNames": "Alternative names",
"oneNamePerLine": "One name per line",
"whatVariationsExist": "What variations of this exercise exist, if any?",
"previous": "Previous",
"next": "Next",
"images": "Images",
"language": "Language",
"addExercise": "Add exercise",
"contributeExercise": "Contribute an exercise",
"translation": "Translation",
"translateExercise": "Translate this exercise now",
"baseData": "Basics in English",
"@baseData": {
"description": "The base data for an exercise such as category, trained muscles, etc."
},
"repetitions": "Repetitions",
"minutes": "Minutes",
"glutes": "Glutes",
"kilometers": "Kilometers",
"until_failure": "Until Failure",
"seconds": "Seconds",
"bench": "Bench",
"barbell": "Barbell",
"triceps": "Triceps",
"swiss_ball": "Swiss Ball",
"none__bodyweight_exercise_": "none (bodyweight exercise)",
"lower_back": "Lower back",
"shoulders": "Shoulders",
"pull_up_bar": "Pull-up bar",
"hamstrings": "Hamstrings",
"calves": "Calves",
"chest": "Chest",
"kettlebell": "Kettlebell",
"biceps": "Biceps",
"dumbbell": "Dumbbell",
"gym_mat": "Gym mat",
"abs": "Abs",
"incline_bench": "Incline bench",
"miles": "Miles",
"lats": "Lats",
"legs": "Legs",
"back": "Back",
"quads": "Quads",
"arms": "Arms",
"sz_bar": "SZ-Bar"
}

View File

@@ -19,15 +19,20 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:wger/providers/add_exercise.dart';
import 'package:wger/providers/base_provider.dart';
import 'package:wger/providers/body_weight.dart';
import 'package:wger/providers/exercises.dart';
import 'package:wger/providers/gallery.dart';
import 'package:wger/providers/measurement.dart';
import 'package:wger/providers/nutrition.dart';
import 'package:wger/providers/user.dart';
import 'package:wger/providers/workout_plans.dart';
import 'package:wger/screens/add_exercise_screen.dart';
import 'package:wger/screens/auth_screen.dart';
import 'package:wger/screens/dashboard.dart';
import 'package:wger/screens/exercise_screen.dart';
import 'package:wger/screens/exercises_screen.dart';
import 'package:wger/screens/form_screen.dart';
import 'package:wger/screens/gallery_screen.dart';
import 'package:wger/screens/gym_mode.dart';
@@ -64,9 +69,10 @@ class MyApp extends StatelessWidget {
create: (ctx) => AuthProvider(),
),
ChangeNotifierProxyProvider<AuthProvider, ExercisesProvider>(
create: (context) =>
ExercisesProvider(Provider.of<AuthProvider>(context, listen: false), []),
update: (context, auth, previous) => previous ?? ExercisesProvider(auth, []),
create: (context) => ExercisesProvider(
WgerBaseProvider(Provider.of<AuthProvider>(context, listen: false))),
update: (context, base, previous) =>
previous ?? ExercisesProvider(WgerBaseProvider(base)),
),
ChangeNotifierProxyProvider2<AuthProvider, ExercisesProvider, WorkoutPlansProvider>(
create: (context) => WorkoutPlansProvider(
@@ -84,10 +90,17 @@ class MyApp extends StatelessWidget {
),
ChangeNotifierProxyProvider<AuthProvider, MeasurementProvider>(
create: (context) => MeasurementProvider(
WgerBaseProvider(Provider.of<AuthProvider>(context, listen: false))),
WgerBaseProvider(Provider.of<AuthProvider>(context, listen: false)),
),
update: (context, base, previous) =>
previous ?? MeasurementProvider(WgerBaseProvider(base)),
),
ChangeNotifierProxyProvider<AuthProvider, UserProvider>(
create: (context) => UserProvider(
WgerBaseProvider(Provider.of<AuthProvider>(context, listen: false)),
),
update: (context, base, previous) => previous ?? UserProvider(WgerBaseProvider(base)),
),
ChangeNotifierProxyProvider<AuthProvider, BodyWeightProvider>(
create: (context) =>
BodyWeightProvider(Provider.of<AuthProvider>(context, listen: false), []),
@@ -98,6 +111,13 @@ class MyApp extends StatelessWidget {
GalleryProvider(Provider.of<AuthProvider>(context, listen: false), []),
update: (context, auth, previous) => previous ?? GalleryProvider(auth, []),
),
ChangeNotifierProxyProvider<AuthProvider, AddExerciseProvider>(
create: (context) => AddExerciseProvider(
WgerBaseProvider(Provider.of<AuthProvider>(context, listen: false)),
),
update: (context, base, previous) =>
previous ?? AddExerciseProvider(WgerBaseProvider(base)),
)
],
child: Consumer<AuthProvider>(
builder: (ctx, auth, _) => MaterialApp(
@@ -132,6 +152,9 @@ class MyApp extends StatelessWidget {
WeightScreen.routeName: (ctx) => WeightScreen(),
WorkoutPlanScreen.routeName: (ctx) => WorkoutPlanScreen(),
WorkoutPlansScreen.routeName: (ctx) => WorkoutPlansScreen(),
ExercisesScreen.routeName: (ctx) => const ExercisesScreen(),
ExerciseDetailScreen.routeName: (ctx) => const ExerciseDetailScreen(),
AddExerciseScreen.routeName: (ctx) => const AddExerciseScreen(),
},
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,

View File

@@ -0,0 +1,43 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 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:json_annotation/json_annotation.dart';
part 'alias.g.dart';
@JsonSerializable()
class Alias {
@JsonKey(required: true)
final int? id;
@JsonKey(required: true, name: 'exercise')
final int exerciseId;
@JsonKey(required: true)
final String alias;
Alias({
this.id,
required this.exerciseId,
required this.alias,
});
// Boilerplate
factory Alias.fromJson(Map<String, dynamic> json) => _$AliasFromJson(json);
Map<String, dynamic> toJson() => _$AliasToJson(this);
}

View File

@@ -0,0 +1,25 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'alias.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Alias _$AliasFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const ['id', 'exercise', 'alias'],
);
return Alias(
id: json['id'] as int?,
exerciseId: json['exercise'] as int,
alias: json['alias'] as String,
);
}
Map<String, dynamic> _$AliasToJson(Alias instance) => <String, dynamic>{
'id': instance.id,
'exercise': instance.exerciseId,
'alias': instance.alias,
};

View File

@@ -0,0 +1,175 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 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:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/consts.dart';
import 'package:wger/models/exercises/category.dart';
import 'package:wger/models/exercises/equipment.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/image.dart';
import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/models/exercises/video.dart';
part 'base.g.dart';
@JsonSerializable(explicitToJson: true)
class ExerciseBase extends Equatable {
@JsonKey(required: true)
final int? id;
@JsonKey(required: true)
final String? uuid;
@JsonKey(required: true, name: 'variations')
final int? variationId;
@JsonKey(required: true, name: 'creation_date')
final DateTime? creationDate;
@JsonKey(required: true, name: 'update_date')
final DateTime? updateDate;
@JsonKey(required: true, name: 'category')
late int categoryId;
@JsonKey(ignore: true)
late final ExerciseCategory category;
@JsonKey(required: true, name: 'muscles')
List<int> musclesIds = [];
@JsonKey(ignore: true)
List<Muscle> muscles = [];
@JsonKey(required: true, name: 'muscles_secondary')
List<int> musclesSecondaryIds = [];
@JsonKey(ignore: true)
List<Muscle> musclesSecondary = [];
@JsonKey(required: true, name: 'equipment')
List<int> equipmentIds = [];
@JsonKey(ignore: true)
List<Equipment> equipment = [];
@JsonKey(ignore: true)
List<ExerciseImage> images = [];
@JsonKey(ignore: true)
List<Exercise> exercises = [];
@JsonKey(ignore: true)
List<Video> videos = [];
ExerciseBase({
this.id,
this.uuid,
this.creationDate,
this.updateDate,
this.variationId,
List<Muscle>? muscles,
List<Muscle>? musclesSecondary,
List<Equipment>? equipment,
List<ExerciseImage>? images,
List<Exercise>? exercises,
ExerciseCategory? category,
List<Video>? videos,
}) {
this.images = images ?? [];
this.equipment = equipment ?? [];
if (category != null) {
this.category = category;
categoryId = category.id;
}
if (muscles != null) {
this.muscles = muscles;
musclesIds = muscles.map((e) => e.id).toList();
}
if (musclesSecondary != null) {
this.musclesSecondary = musclesSecondary;
musclesSecondaryIds = musclesSecondary.map((e) => e.id).toList();
}
if (equipment != null) {
this.equipment = equipment;
equipmentIds = equipment.map((e) => e.id).toList();
}
if (exercises != null) {
this.exercises = exercises;
}
if (videos != null) {
this.videos = videos;
}
}
/// Returns exercises for the given language
///
/// If no translation is found, English will be returned
///
/// Note: we return the first translation as a fallback if we don't find a
/// translation in English. This is something that should never happen,
/// but we can't make sure that no local installation hasn't deleted
/// the entry in English.
Exercise getExercise(String language) {
// If the language is in the form en-US, take the language code only
final languageCode = language.split('-')[0];
return exercises.firstWhere(
(e) => e.languageObj.shortName == languageCode,
orElse: () => exercises.firstWhere(
(e) => e.languageObj.shortName == LANGUAGE_SHORT_ENGLISH,
orElse: () => exercises.first,
),
);
}
ExerciseImage? get getMainImage {
try {
return images.firstWhere((image) => image.isMain);
} on StateError {
return null;
}
}
set setCategory(ExerciseCategory category) {
categoryId = category.id;
this.category = category;
}
// Boilerplate
factory ExerciseBase.fromJson(Map<String, dynamic> json) => _$ExerciseBaseFromJson(json);
Map<String, dynamic> toJson() => _$ExerciseBaseToJson(this);
@override
List<Object?> get props => [
id,
uuid,
creationDate,
updateDate,
category,
equipment,
muscles,
musclesSecondary,
];
}

View File

@@ -0,0 +1,49 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'base.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ExerciseBase _$ExerciseBaseFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const [
'id',
'uuid',
'variations',
'creation_date',
'update_date',
'category',
'muscles',
'muscles_secondary',
'equipment'
],
);
return ExerciseBase(
id: json['id'] as int?,
uuid: json['uuid'] as String?,
creationDate:
json['creation_date'] == null ? null : DateTime.parse(json['creation_date'] as String),
updateDate: json['update_date'] == null ? null : DateTime.parse(json['update_date'] as String),
variationId: json['variations'] as int?,
)
..categoryId = json['category'] as int
..musclesIds = (json['muscles'] as List<dynamic>).map((e) => e as int).toList()
..musclesSecondaryIds =
(json['muscles_secondary'] as List<dynamic>).map((e) => e as int).toList()
..equipmentIds = (json['equipment'] as List<dynamic>).map((e) => e as int).toList();
}
Map<String, dynamic> _$ExerciseBaseToJson(ExerciseBase instance) => <String, dynamic>{
'id': instance.id,
'uuid': instance.uuid,
'variations': instance.variationId,
'creation_date': instance.creationDate?.toIso8601String(),
'update_date': instance.updateDate?.toIso8601String(),
'category': instance.categoryId,
'muscles': instance.musclesIds,
'muscles_secondary': instance.musclesSecondaryIds,
'equipment': instance.equipmentIds,
};

View File

@@ -16,12 +16,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'category.g.dart';
@JsonSerializable()
class ExerciseCategory {
class ExerciseCategory extends Equatable {
@JsonKey(required: true)
final int id;
@@ -35,10 +36,13 @@ class ExerciseCategory {
@override
String toString() {
return 'Category $id';
return 'Category $id: $name';
}
// Boilerplate
factory ExerciseCategory.fromJson(Map<String, dynamic> json) => _$ExerciseCategoryFromJson(json);
Map<String, dynamic> toJson() => _$ExerciseCategoryToJson(this);
@override
List<Object?> get props => [id, name];
}

View File

@@ -25,11 +25,15 @@ class Comment {
@JsonKey(required: true)
final int id;
@JsonKey(required: true, name: 'exercise')
final int exerciseId;
@JsonKey(required: true)
final String comment;
Comment({
required this.id,
required this.exerciseId,
required this.comment,
});

View File

@@ -9,15 +9,17 @@ part of 'comment.dart';
Comment _$CommentFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const ['id', 'comment'],
requiredKeys: const ['id', 'exercise', 'comment'],
);
return Comment(
id: json['id'] as int,
exerciseId: json['exercise'] as int,
comment: json['comment'] as String,
);
}
Map<String, dynamic> _$CommentToJson(Comment instance) => <String, dynamic>{
'id': instance.id,
'exercise': instance.exerciseId,
'comment': instance.comment,
};

View File

@@ -16,12 +16,13 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'equipment.g.dart';
@JsonSerializable()
class Equipment {
class Equipment extends Equatable {
@JsonKey(required: true)
final int id;
@@ -36,4 +37,12 @@ class Equipment {
// Boilerplate
factory Equipment.fromJson(Map<String, dynamic> json) => _$EquipmentFromJson(json);
Map<String, dynamic> toJson() => _$EquipmentToJson(this);
@override
List<Object?> get props => [id, name];
@override
String toString() {
return 'Equipment: $id - $name';
}
}

View File

@@ -16,26 +16,34 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/exercises/category.dart';
import 'package:wger/models/exercises/alias.dart';
import 'package:wger/models/exercises/base.dart';
import 'package:wger/models/exercises/comment.dart';
import 'package:wger/models/exercises/equipment.dart';
import 'package:wger/models/exercises/image.dart';
import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/models/exercises/video.dart';
import 'package:wger/models/exercises/language.dart';
part 'exercise.g.dart';
@JsonSerializable(explicitToJson: true)
class Exercise {
@JsonSerializable()
class Exercise extends Equatable {
@JsonKey(required: true)
final int id;
final int? id;
@JsonKey(required: true)
final String uuid;
final String? uuid;
@JsonKey(required: true, name: 'language')
late int languageId;
@JsonKey(ignore: true)
late Language languageObj;
@JsonKey(required: true, name: 'creation_date')
final DateTime creationDate;
final DateTime? creationDate;
@JsonKey(required: true, name: 'exercise_base')
late int? baseId;
@JsonKey(required: true)
final String name;
@@ -43,69 +51,52 @@ class Exercise {
@JsonKey(required: true)
final String description;
@JsonKey(required: false, ignore: true)
late int categoryId;
@JsonKey(ignore: true)
List<Comment> notes = [];
@JsonKey(required: true, name: 'category')
late final ExerciseCategory categoryObj;
@JsonKey(ignore: true)
List<Alias> alias = [];
@JsonKey(required: true)
List<Muscle> muscles = [];
Exercise({
this.id,
this.uuid,
this.creationDate,
required this.name,
required this.description,
int? baseId,
language,
}) {
if (baseId != null) {
baseId = baseId;
}
@JsonKey(required: true, name: 'muscles_secondary')
List<Muscle> musclesSecondary = [];
@JsonKey(required: true)
List<Equipment> equipment = [];
@JsonKey(required: true)
List<ExerciseImage> images = [];
@JsonKey(required: true)
List<Video> videos = [];
@JsonKey(required: true, name: 'comments')
List<Comment> tips = [];
Exercise(
{required this.id,
required this.uuid,
required this.creationDate,
required this.name,
required this.description,
List<Muscle>? muscles,
List<Muscle>? musclesSecondary,
List<Equipment>? equipment,
List<ExerciseImage>? images,
List<Video>? videos,
List<Comment>? tips,
ExerciseCategory? category}) {
this.tips = tips ?? [];
this.images = images ?? [];
this.videos = videos ?? [];
this.equipment = equipment ?? [];
this.musclesSecondary = musclesSecondary ?? [];
this.muscles = muscles ?? [];
if (category != null) {
categoryObj = category;
categoryId = category.id;
if (language != null) {
languageObj = language;
languageId = language.id;
}
}
ExerciseImage? get getMainImage {
try {
return images.firstWhere((image) => image.isMain);
} on StateError {
return null;
}
set base(ExerciseBase base) {
baseId = base.id;
}
set category(ExerciseCategory category) {
categoryId = category.id;
categoryObj = category;
set language(Language language) {
languageObj = language;
languageId = language.id;
}
// Boilerplate
factory Exercise.fromJson(Map<String, dynamic> json) => _$ExerciseFromJson(json);
Map<String, dynamic> toJson() => _$ExerciseToJson(this);
@override
List<Object?> get props => [
id,
baseId,
uuid,
languageId,
creationDate,
name,
description,
];
}

View File

@@ -12,56 +12,30 @@ Exercise _$ExerciseFromJson(Map<String, dynamic> json) {
requiredKeys: const [
'id',
'uuid',
'language',
'creation_date',
'exercise_base',
'name',
'description',
'category',
'muscles',
'muscles_secondary',
'equipment',
'images',
'videos',
'comments'
'description'
],
);
return Exercise(
id: json['id'] as int,
uuid: json['uuid'] as String,
creationDate: DateTime.parse(json['creation_date'] as String),
id: json['id'] as int?,
uuid: json['uuid'] as String?,
creationDate:
json['creation_date'] == null ? null : DateTime.parse(json['creation_date'] as String),
name: json['name'] as String,
description: json['description'] as String,
muscles: (json['muscles'] as List<dynamic>?)
?.map((e) => Muscle.fromJson(e as Map<String, dynamic>))
.toList(),
musclesSecondary: (json['muscles_secondary'] as List<dynamic>?)
?.map((e) => Muscle.fromJson(e as Map<String, dynamic>))
.toList(),
equipment: (json['equipment'] as List<dynamic>?)
?.map((e) => Equipment.fromJson(e as Map<String, dynamic>))
.toList(),
images: (json['images'] as List<dynamic>?)
?.map((e) => ExerciseImage.fromJson(e as Map<String, dynamic>))
.toList(),
videos: (json['videos'] as List<dynamic>?)
?.map((e) => Video.fromJson(e as Map<String, dynamic>))
.toList(),
tips: (json['comments'] as List<dynamic>?)
?.map((e) => Comment.fromJson(e as Map<String, dynamic>))
.toList(),
)..categoryObj = ExerciseCategory.fromJson(json['category'] as Map<String, dynamic>);
baseId: json['exercise_base'] as int?,
)..languageId = json['language'] as int;
}
Map<String, dynamic> _$ExerciseToJson(Exercise instance) => <String, dynamic>{
'id': instance.id,
'uuid': instance.uuid,
'creation_date': instance.creationDate.toIso8601String(),
'language': instance.languageId,
'creation_date': instance.creationDate?.toIso8601String(),
'exercise_base': instance.baseId,
'name': instance.name,
'description': instance.description,
'category': instance.categoryObj.toJson(),
'muscles': instance.muscles.map((e) => e.toJson()).toList(),
'muscles_secondary': instance.musclesSecondary.map((e) => e.toJson()).toList(),
'equipment': instance.equipment.map((e) => e.toJson()).toList(),
'images': instance.images.map((e) => e.toJson()).toList(),
'videos': instance.videos.map((e) => e.toJson()).toList(),
'comments': instance.tips.map((e) => e.toJson()).toList(),
};

View File

@@ -48,4 +48,9 @@ class ExerciseImage {
// Boilerplate
factory ExerciseImage.fromJson(Map<String, dynamic> json) => _$ExerciseImageFromJson(json);
Map<String, dynamic> toJson() => _$ExerciseImageToJson(this);
@override
String toString() {
return 'Image $id: $url';
}
}

View File

@@ -0,0 +1,47 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 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:equatable/equatable.dart';
import 'package:json_annotation/json_annotation.dart';
part 'language.g.dart';
@JsonSerializable()
class Language extends Equatable {
@JsonKey(required: true)
final int id;
@JsonKey(required: true, name: 'short_name')
final String shortName;
@JsonKey(required: true, name: 'full_name')
final String fullName;
const Language({
required this.id,
required this.shortName,
required this.fullName,
});
// Boilerplate
factory Language.fromJson(Map<String, dynamic> json) => _$LanguageFromJson(json);
Map<String, dynamic> toJson() => _$LanguageToJson(this);
@override
List<Object?> get props => [id, shortName, fullName];
}

View File

@@ -0,0 +1,25 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'language.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Language _$LanguageFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const ['id', 'short_name', 'full_name'],
);
return Language(
id: json['id'] as int,
shortName: json['short_name'] as String,
fullName: json['full_name'] as String,
);
}
Map<String, dynamic> _$LanguageToJson(Language instance) => <String, dynamic>{
'id': instance.id,
'short_name': instance.shortName,
'full_name': instance.fullName,
};

View File

@@ -16,28 +16,47 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'package:equatable/equatable.dart';
import 'package:flutter/widgets.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/i18n.dart';
part 'muscle.g.dart';
@JsonSerializable()
class Muscle {
class Muscle extends Equatable {
@JsonKey(required: true)
final int id;
@JsonKey(required: true)
final String name;
@JsonKey(required: true, name: 'name_en')
final String nameEn;
@JsonKey(name: 'is_front', required: true)
final bool isFront;
const Muscle({
required this.id,
required this.name,
required this.nameEn,
required this.isFront,
});
// Boilerplate
factory Muscle.fromJson(Map<String, dynamic> json) => _$MuscleFromJson(json);
Map<String, dynamic> toJson() => _$MuscleToJson(this);
@override
List<Object?> get props => [id, name, isFront];
String nameTranslated(BuildContext context) {
return name + (nameEn.isNotEmpty ? ' (${getTranslation(nameEn, context)})' : '');
}
@override
String toString() {
return 'Muscle: $id - $name';
}
}

View File

@@ -9,11 +9,12 @@ part of 'muscle.dart';
Muscle _$MuscleFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const ['id', 'name', 'is_front'],
requiredKeys: const ['id', 'name', 'name_en', 'is_front'],
);
return Muscle(
id: json['id'] as int,
name: json['name'] as String,
nameEn: json['name_en'] as String,
isFront: json['is_front'] as bool,
);
}
@@ -21,5 +22,6 @@ Muscle _$MuscleFromJson(Map<String, dynamic> json) {
Map<String, dynamic> _$MuscleToJson(Muscle instance) => <String, dynamic>{
'id': instance.id,
'name': instance.name,
'name_en': instance.nameEn,
'is_front': instance.isFront,
};

View File

@@ -0,0 +1,35 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 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:json_annotation/json_annotation.dart';
part 'variation.g.dart';
@JsonSerializable()
class Variation {
@JsonKey(required: true)
final int id;
Variation({
required this.id,
});
// Boilerplate
factory Variation.fromJson(Map<String, dynamic> json) => _$VariationFromJson(json);
Map<String, dynamic> toJson() => _$VariationToJson(this);
}

View File

@@ -0,0 +1,21 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'variation.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Variation _$VariationFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const ['id'],
);
return Variation(
id: json['id'] as int,
);
}
Map<String, dynamic> _$VariationToJson(Variation instance) => <String, dynamic>{
'id': instance.id,
};

View File

@@ -53,10 +53,15 @@ class MealItem {
required this.ingredientId,
this.weightUnitId,
required this.amount,
Ingredient? ingredient,
}) {
if (mealId != null) {
this.mealId = mealId;
}
if (ingredient != null) {
ingredientObj = ingredient;
ingredientId = ingredient.id;
}
}
MealItem.empty();

View File

@@ -0,0 +1,43 @@
/*
* This file is part of wger Workout Manager <https://github.com/wger-project>.
* Copyright (C) 2020, 2021 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,
* 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:json_annotation/json_annotation.dart';
part 'profile.g.dart';
@JsonSerializable()
class Profile {
@JsonKey(required: true)
String username;
@JsonKey(required: true, name: 'email_verified')
bool emailVerified;
@JsonKey(required: true)
String email;
Profile({
required this.username,
required this.emailVerified,
required this.email,
});
// Boilerplate
factory Profile.fromJson(Map<String, dynamic> json) => _$ProfileFromJson(json);
Map<String, dynamic> toJson() => _$ProfileToJson(this);
}

View File

@@ -0,0 +1,25 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'profile.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
Profile _$ProfileFromJson(Map<String, dynamic> json) {
$checkKeys(
json,
requiredKeys: const ['username', 'email_verified', 'email'],
);
return Profile(
username: json['username'] as String,
emailVerified: json['email_verified'] as bool,
email: json['email'] as String,
);
}
Map<String, dynamic> _$ProfileToJson(Profile instance) => <String, dynamic>{
'username': instance.username,
'email_verified': instance.emailVerified,
'email': instance.email,
};

View File

@@ -16,12 +16,10 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import 'dart:ui';
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/base.dart';
import 'package:wger/models/workouts/repetition_unit.dart';
import 'package:wger/models/workouts/weight_unit.dart';
@@ -32,11 +30,11 @@ class Log {
@JsonKey(required: true)
int? id;
@JsonKey(required: true, name: 'exercise')
late int exerciseId;
@JsonKey(required: true, name: 'exercise_base')
late int exerciseBaseId;
@JsonKey(ignore: true)
late Exercise exerciseObj;
late ExerciseBase exerciseBaseObj;
@JsonKey(required: true, name: 'workout')
late int workoutPlan;
@@ -70,7 +68,7 @@ class Log {
Log({
this.id,
required this.exerciseId,
required this.exerciseBaseId,
required this.workoutPlan,
required this.reps,
required this.rir,
@@ -86,9 +84,9 @@ class Log {
factory Log.fromJson(Map<String, dynamic> json) => _$LogFromJson(json);
Map<String, dynamic> toJson() => _$LogToJson(this);
set exercise(Exercise exercise) {
exerciseObj = exercise;
exerciseId = exercise.id;
set exerciseBase(ExerciseBase base) {
exerciseBaseObj = base;
exerciseBaseId = base.id!;
}
set weightUnit(WeightUnit weightUnit) {
@@ -123,7 +121,7 @@ class Log {
//ignore: avoid_equals_and_hash_code_on_mutable_classes
bool operator ==(o) {
return o is Log &&
exerciseId == o.exerciseId &&
exerciseBaseId == o.exerciseBaseId &&
weight == o.weight &&
weightUnitId == o.weightUnitId &&
reps == o.reps &&
@@ -133,13 +131,14 @@ class Log {
@override
//ignore: avoid_equals_and_hash_code_on_mutable_classes
int get hashCode => Object.hash(exerciseId, weight, weightUnitId, reps, repetitionUnitId, rir);
int get hashCode =>
Object.hash(exerciseBaseId, weight, weightUnitId, reps, repetitionUnitId, rir);
//@override
//int get hashCode => super.hashCode;
@override
String toString() {
return 'Log(id: $id, ex: $exerciseId, weightU: $weightUnitId, w: $weight, repU: $repetitionUnitId, rep: $reps, rir: $rir)';
return 'Log(id: $id, ex: $exerciseBaseId, weightU: $weightUnitId, w: $weight, repU: $repetitionUnitId, rep: $reps, rir: $rir)';
}
}

View File

@@ -11,7 +11,7 @@ Log _$LogFromJson(Map<String, dynamic> json) {
json,
requiredKeys: const [
'id',
'exercise',
'exercise_base',
'workout',
'reps',
'repetition_unit',
@@ -22,7 +22,7 @@ Log _$LogFromJson(Map<String, dynamic> json) {
);
return Log(
id: json['id'] as int?,
exerciseId: json['exercise'] as int,
exerciseBaseId: json['exercise_base'] as int,
workoutPlan: json['workout'] as int,
reps: json['reps'] as int,
rir: json['rir'] as String?,
@@ -35,7 +35,7 @@ Log _$LogFromJson(Map<String, dynamic> json) {
Map<String, dynamic> _$LogToJson(Log instance) => <String, dynamic>{
'id': instance.id,
'exercise': instance.exerciseId,
'exercise_base': instance.exerciseBaseId,
'workout': instance.workoutPlan,
'reps': instance.reps,
'rir': instance.rir,

View File

@@ -17,7 +17,7 @@
*/
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/base.dart';
import 'package:wger/models/workouts/setting.dart';
part 'set.g.dart';
@@ -42,10 +42,10 @@ class Set {
late String comment;
@JsonKey(ignore: true)
List<Exercise> exercisesObj = [];
List<ExerciseBase> exerciseBasesObj = [];
@JsonKey(ignore: true)
List<int> exercisesIds = [];
List<int> exerciseBasesIds = [];
@JsonKey(ignore: true)
List<Setting> settings = [];
@@ -76,8 +76,8 @@ class Set {
this.sets = sets ?? DEFAULT_NR_SETS;
this.order = order ?? 1;
this.comment = comment ?? '';
exercisesObj = exercises ?? [];
exercisesIds = exercisesObj.map((e) => e.id).toList();
exerciseBasesObj = exercises ?? [];
exerciseBasesIds = exerciseBasesObj.map((e) => e.id!).toList();
this.settings = settings ?? [];
this.settingsComputed = settingsComputed ?? [];
if (day != null) {
@@ -92,7 +92,7 @@ class Set {
for (final setting in settings) {
final foundSettings = out.where(
(element) => element.exerciseId == setting.exerciseId,
(element) => element.exerciseBaseId == setting.exerciseBaseId,
);
if (foundSettings.isEmpty) {
@@ -102,26 +102,26 @@ class Set {
return out;
}
void addExercise(Exercise exercise) {
exercisesObj.add(exercise);
exercisesIds.add(exercise.id);
void addExerciseBase(ExerciseBase base) {
exerciseBasesObj.add(base);
exerciseBasesIds.add(base.id!);
}
void removeExercise(Exercise exercise) {
exercisesObj.removeWhere((e) => e.id == exercise.id);
exercisesIds.removeWhere((e) => e == exercise.id);
void removeExercise(ExerciseBase base) {
exerciseBasesObj.removeWhere((e) => e.id == base.id);
exerciseBasesIds.removeWhere((e) => e == base.id);
}
/// Returns all settings for the given exercise
List<Setting> filterSettingsByExercise(Exercise exercise) {
return settings.where((element) => element.exerciseId == exercise.id).toList();
List<Setting> filterSettingsByExercise(ExerciseBase exerciseBase) {
return settings.where((element) => element.exerciseBaseId == exerciseBase.id).toList();
}
/// Returns a list with all repetitions for the given exercise
List<String> getSmartRepr(Exercise exercise) {
List<String> getSmartRepr(ExerciseBase exerciseBase) {
final List<String> out = [];
final settingList = filterSettingsByExercise(exercise);
final settingList = filterSettingsByExercise(exerciseBase);
if (settingList.isEmpty) {
out.add('');
@@ -141,8 +141,8 @@ class Set {
}
/// Returns a string with all repetitions for the given exercise
String getSmartTextRepr(Exercise exercise) {
return getSmartRepr(exercise).join(' – ');
String getSmartTextRepr(ExerciseBase execiseBase) {
return getSmartRepr(execiseBase).join(' – ');
}
// Boilerplate

View File

@@ -19,7 +19,7 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/helpers/json.dart';
import 'package:wger/helpers/misc.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/base.dart';
import 'package:wger/models/workouts/repetition_unit.dart';
import 'package:wger/models/workouts/weight_unit.dart';
@@ -42,10 +42,10 @@ class Setting {
late int order;
@JsonKey(ignore: true)
late Exercise exerciseObj;
late ExerciseBase exerciseBaseObj;
@JsonKey(required: true, name: 'exercise')
late int exerciseId;
@JsonKey(required: true, name: 'exercise_base')
late int exerciseBaseId;
@JsonKey(required: true, name: 'repetition_unit')
late int repetitionUnitId;
@@ -77,7 +77,7 @@ class Setting {
this.id,
required this.setId,
required this.order,
required this.exerciseId,
required this.exerciseBaseId,
required this.repetitionUnitId,
required this.reps,
required this.weightUnitId,
@@ -91,9 +91,9 @@ class Setting {
factory Setting.fromJson(Map<String, dynamic> json) => _$SettingFromJson(json);
Map<String, dynamic> toJson() => _$SettingToJson(this);
set exercise(Exercise exercise) {
exerciseObj = exercise;
exerciseId = exercise.id;
set exerciseBase(ExerciseBase exerciseBase) {
exerciseBaseObj = exerciseBase;
exerciseBaseId = exerciseBase.id!;
}
set weightUnit(WeightUnit weightUnit) {

View File

@@ -13,7 +13,7 @@ Setting _$SettingFromJson(Map<String, dynamic> json) {
'id',
'set',
'order',
'exercise',
'exercise_base',
'repetition_unit',
'reps',
'weight',
@@ -26,7 +26,7 @@ Setting _$SettingFromJson(Map<String, dynamic> json) {
id: json['id'] as int?,
setId: json['set'] as int,
order: json['order'] as int,
exerciseId: json['exercise'] as int,
exerciseBaseId: json['exercise_base'] as int,
repetitionUnitId: json['repetition_unit'] as int,
reps: json['reps'] as int?,
weightUnitId: json['weight_unit'] as int,
@@ -39,7 +39,7 @@ Map<String, dynamic> _$SettingToJson(Setting instance) => <String, dynamic>{
'id': instance.id,
'set': instance.setId,
'order': instance.order,
'exercise': instance.exerciseId,
'exercise_base': instance.exerciseBaseId,
'repetition_unit': instance.repetitionUnitId,
'reps': instance.reps,
'weight': numToString(instance.weight),

View File

@@ -17,6 +17,7 @@
*/
import 'package:json_annotation/json_annotation.dart';
import 'package:wger/models/exercises/base.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/workouts/day.dart';
import 'package:wger/models/workouts/log.dart';
@@ -72,8 +73,8 @@ class WorkoutPlan {
/// means here that the values are the same, i.e. logs with the same weight,
/// reps, etc. are considered equal. Workout ID, Log ID and date are not
/// considered.
List<Log> filterLogsByExercise(Exercise exercise, {bool unique = false}) {
var out = logs.where((element) => element.exerciseId == exercise.id).toList();
List<Log> filterLogsByExerciseBase(ExerciseBase exerciseBase, {bool unique = false}) {
var out = logs.where((element) => element.exerciseBaseId == exerciseBase.id).toList();
if (unique) {
out = out.toSet().toList();
@@ -88,7 +89,7 @@ class WorkoutPlan {
Map<DateTime, Map<String, dynamic>> get logData {
final out = <DateTime, Map<String, dynamic>>{};
for (final log in logs) {
final exercise = log.exerciseObj;
final exercise = log.exerciseBaseObj;
final date = log.date;
if (!out.containsKey(date)) {

View File

@@ -0,0 +1,261 @@
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:wger/helpers/consts.dart';
import 'package:wger/models/exercises/alias.dart';
import 'package:wger/models/exercises/base.dart';
import 'package:wger/models/exercises/category.dart';
import 'package:wger/models/exercises/equipment.dart';
import 'package:wger/models/exercises/exercise.dart';
import 'package:wger/models/exercises/language.dart';
import 'package:wger/models/exercises/muscle.dart';
import 'package:wger/models/exercises/variation.dart';
import 'base_provider.dart';
class AddExerciseProvider with ChangeNotifier {
final WgerBaseProvider baseProvider;
AddExerciseProvider(this.baseProvider);
List<File> get exerciseImages => [..._exerciseImages];
List<File> _exerciseImages = [];
String? _nameEn;
String? _nameTranslation;
String? _descriptionEn;
String? _descriptionTranslation;
int? _variationId;
int? _newVariationForExercise;
Language? language;
List<String> _alternativeNamesEn = [];
List<String> _alternativeNamesTranslation = [];
ExerciseCategory? category;
List<ExerciseBase> _variations = [];
List<Equipment> _equipment = [];
List<Muscle> _primaryMuscles = [];
List<Muscle> _secondaryMuscles = [];
static const _exerciseBaseUrlPath = 'exercise-base';
static const _imagesUrlPath = 'exerciseimage';
static const _exerciseTranslationUrlPath = 'exercise-translation';
static const _exerciseAliasPath = 'exercisealias';
static const _exerciseVariationPath = 'variation';
void clear() {
_exerciseImages = [];
language = null;
category = null;
_nameEn = null;
_nameTranslation = null;
_descriptionEn = null;
_descriptionTranslation = null;
_alternativeNamesEn = [];
_alternativeNamesTranslation = [];
_variations = [];
_equipment = [];
_primaryMuscles = [];
_secondaryMuscles = [];
}
set exerciseNameEn(String name) => _nameEn = name;
set exerciseNameTrans(String name) => _nameTranslation = name;
set descriptionEn(String description) => _descriptionEn = description;
set descriptionTrans(String description) => _descriptionTranslation = description;
set alternateNamesEn(List<String> names) => _alternativeNamesEn = names;
set alternateNamesTrans(List<String> names) => _alternativeNamesTranslation = names;
set equipment(List<Equipment> equipment) => _equipment = equipment;
List<Equipment> get equipment => [..._equipment];
bool get newVariation => _newVariationForExercise != null;
int? get newVariationForExercise => _newVariationForExercise;
set newVariationForExercise(int? value) {
_newVariationForExercise = value;
_variationId = null;
notifyListeners();
}
int? get variationId => _variationId;
set variationId(int? variation) {
_variationId = variation;
_newVariationForExercise = null;
notifyListeners();
}
ExerciseBase get base {
return ExerciseBase(
category: category,
equipment: _equipment,
muscles: _primaryMuscles,
musclesSecondary: _secondaryMuscles,
variationId: _variationId,
);
}
Exercise get exerciseEn {
return Exercise(
name: _nameEn!,
description: _descriptionEn!,
language: const Language(id: 2, fullName: 'English', shortName: 'en'),
);
}
Exercise get exerciseTranslation {
return Exercise(
name: _nameTranslation!,
description: _descriptionTranslation!,
language: language,
);
}
Variation get variation {
return Variation(id: _variationId!);
}
List<Muscle> get primaryMuscles => [..._primaryMuscles];
set primaryMuscles(List<Muscle> muscles) {
_primaryMuscles = muscles;
notifyListeners();
}
List<Muscle> get secondaryMuscles => [..._secondaryMuscles];
set secondaryMuscles(List<Muscle> muscles) {
_secondaryMuscles = muscles;
notifyListeners();
}
void addExerciseImages(List<File> exercises) {
_exerciseImages.addAll(exercises);
notifyListeners();
}
void removeExercise(String path) {
final file = _exerciseImages.where((element) => element.path == path).first;
_exerciseImages.remove(file);
notifyListeners();
}
//Just to Debug Provider
void printValues() {
log('Collected exercise data');
log('------------------------');
log('Base data...');
log('Target area : $category');
log('Primary muscles: $_primaryMuscles');
log('Secondary muscles: $_secondaryMuscles');
log('Equipment: $_equipment');
log('Variations: $_variations');
log('');
log('Language specific...');
log('Language: ${language?.shortName}');
log('Name: en/$_nameEn translation/$_nameTranslation');
log('Description: en/$_descriptionEn translation/$_descriptionTranslation');
log('Alternate names: en/$_alternativeNamesEn translation/$_alternativeNamesTranslation');
}
Future<int> addExercise() async {
printValues();
// Create the variations if needed
if (newVariation) {
await addVariation();
}
// Create the base
final base = await addExerciseBase();
// Create the base description in English
Exercise exerciseTranslationEn = exerciseEn;
exerciseTranslationEn.base = base;
exerciseTranslationEn = await addExerciseTranslation(exerciseTranslationEn);
for (final alias in _alternativeNamesEn) {
if (alias.isNotEmpty) {
exerciseTranslationEn.alias.add(await addExerciseAlias(alias, exerciseTranslationEn.id!));
}
}
// Create the translations
if (language != null) {
Exercise exerciseTranslationLang = exerciseTranslation;
exerciseTranslationLang.base = base;
exerciseTranslationLang = await addExerciseTranslation(exerciseTranslationLang);
for (final alias in _alternativeNamesTranslation) {
if (alias.isNotEmpty) {
exerciseTranslationLang.alias.add(
await addExerciseAlias(alias, exerciseTranslationLang.id!),
);
}
}
await addExerciseTranslation(exerciseTranslationLang);
}
// Clear everything
//clear();
// Create the images
await addImages(base);
// Return exercise ID
return exerciseTranslationEn.id!;
}
Future<ExerciseBase> addExerciseBase() async {
final Uri postUri = baseProvider.makeUrl(_exerciseBaseUrlPath);
final Map<String, dynamic> newBaseMap = await baseProvider.post(base.toJson(), postUri);
final ExerciseBase newExerciseBase = ExerciseBase.fromJson(newBaseMap);
notifyListeners();
return newExerciseBase;
}
Future<Variation> addVariation() async {
final Uri postUri = baseProvider.makeUrl(_exerciseVariationPath);
// We send an empty dictionary since at the moment the variations only have an ID
final Map<String, dynamic> variationMap = await baseProvider.post({}, postUri);
final Variation newVariation = Variation.fromJson(variationMap);
_variationId = newVariation.id;
notifyListeners();
return newVariation;
}
Future<void> addImages(ExerciseBase base) async {
for (final image in _exerciseImages) {
final request = http.MultipartRequest('POST', baseProvider.makeUrl(_imagesUrlPath));
request.headers.addAll(baseProvider.getDefaultHeaders(includeAuth: true));
request.files.add(await http.MultipartFile.fromPath('image', image.path));
request.fields['exercise_base'] = base.id!.toString();
request.fields['style'] = EXERCISE_IMAGE_ART_STYLE.PHOTO.index.toString();
await request.send();
}
notifyListeners();
}
Future<Exercise> addExerciseTranslation(Exercise exercise) async {
final Uri postUri = baseProvider.makeUrl(_exerciseTranslationUrlPath);
final Map<String, dynamic> newTranslation = await baseProvider.post(exercise.toJson(), postUri);
final Exercise newExercise = Exercise.fromJson(newTranslation);
notifyListeners();
return newExercise;
}
Future<Alias> addExerciseAlias(String name, int exerciseId) async {
final alias = Alias(exerciseId: exerciseId, alias: name);
final Uri postUri = baseProvider.makeUrl(_exerciseAliasPath);
final Alias newAlias = Alias.fromJson(await baseProvider.post(alias.toJson(), postUri));
notifyListeners();
return newAlias;
}
}

Some files were not shown because too many files have changed in this diff Show More