mirror of
https://github.com/wger-project/flutter.git
synced 2026-11-30 01:41:05 +01:00
Merge pull request #1183 from wger-project/feature/offline-mode
Add offline mode and move the providers to riverpos
This commit is contained in:
2
.github/actions/flutter-common/action.yml
vendored
2
.github/actions/flutter-common/action.yml
vendored
@@ -9,7 +9,7 @@ runs:
|
||||
uses: subosito/flutter-action@v2
|
||||
with:
|
||||
channel: stable
|
||||
flutter-version: 3.41.9
|
||||
flutter-version: 3.44.0
|
||||
cache: true
|
||||
|
||||
- name: Install Flutter dependencies
|
||||
|
||||
4
.github/workflows/build-linux.yml
vendored
4
.github/workflows/build-linux.yml
vendored
@@ -61,7 +61,7 @@ jobs:
|
||||
- name: Build application for linux
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev --no-install-recommends
|
||||
sudo apt install -y pkg-config libgtk-3-dev liblzma-dev libstdc++-12-dev libsecret-1-dev libjsoncpp-dev --no-install-recommends
|
||||
flutter build linux --release
|
||||
tar -zcvf linux-${{ matrix.platform }}.tar.gz build/linux/${{ matrix.platform }}/release/bundle
|
||||
- uses: actions/upload-artifact@v7
|
||||
@@ -92,7 +92,7 @@ jobs:
|
||||
git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.14.1 ../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.json
|
||||
../flatpak-flutter/flatpak-flutter.py --app-module wger flatpak-flutter.yml
|
||||
|
||||
- name: Push updated config to flathub repository
|
||||
env:
|
||||
|
||||
6
.github/workflows/screenshots.yml
vendored
6
.github/workflows/screenshots.yml
vendored
@@ -20,12 +20,6 @@ jobs:
|
||||
- name: Common flutter setup
|
||||
uses: ./.github/actions/flutter-common
|
||||
|
||||
- name: Install CocoaPods
|
||||
run: |
|
||||
cd ios
|
||||
pod install || true
|
||||
cd ..
|
||||
|
||||
- name: Boot iOS simulator
|
||||
id: boot
|
||||
run: |
|
||||
|
||||
@@ -49,6 +49,15 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
|
||||
<!-- Web-handoff deep link: the server redirects to wger://app-auth#token=…
|
||||
after a browser login; app_link_router consumes the URI. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="wger" android:host="app-auth" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
|
||||
|
||||
6
build.yaml
Normal file
6
build.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
targets:
|
||||
$default:
|
||||
builders:
|
||||
drift_dev:
|
||||
options:
|
||||
store_date_time_values_as_text: true
|
||||
@@ -1,3 +1,4 @@
|
||||
extensions:
|
||||
- drift: true
|
||||
- provider: true
|
||||
- provider: true
|
||||
- shared_preferences: true
|
||||
@@ -8,7 +8,8 @@ Comment=Fitness/workout, nutrition and weight tracker
|
||||
# HealthFitness;Exercise;Nutrition
|
||||
Categories=Education;Utility;Sports;
|
||||
Icon=de.wger.flutter
|
||||
Exec=wger
|
||||
Exec=wger %u
|
||||
MimeType=x-scheme-handler/wger;
|
||||
StartupWMClass=wger
|
||||
X-Purism-FormFactor=Workstation;Mobile;
|
||||
X-KDE-FormFactors=desktop;tablet;handset;mediacenter;
|
||||
|
||||
3
flatpak/de.wger.flutter.service
Normal file
3
flatpak/de.wger.flutter.service
Normal file
@@ -0,0 +1,3 @@
|
||||
[D-BUS Service]
|
||||
Name=de.wger.flutter
|
||||
Exec=/app/bin/wger --gapplication-service
|
||||
@@ -44,8 +44,7 @@ enum DeviceType {
|
||||
androidWear('wearScreenshots'),
|
||||
|
||||
iOSPhoneBig('iPhone 6.9', isAndroid: false),
|
||||
iOSPhoneSmall('iPhone 6.7', isAndroid: false)
|
||||
;
|
||||
iOSPhoneSmall('iPhone 6.7', isAndroid: false);
|
||||
|
||||
final String folderName;
|
||||
final bool isAndroid;
|
||||
|
||||
@@ -17,131 +17,112 @@
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod;
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/models/workouts/session.dart';
|
||||
import 'package:wger/providers/auth.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/routines.dart';
|
||||
import 'package:wger/providers/user.dart';
|
||||
import 'package:wger/models/measurements/measurement_category.dart';
|
||||
import 'package:wger/providers/auth_notifier.dart';
|
||||
import 'package:wger/providers/auth_state.dart';
|
||||
import 'package:wger/providers/body_weight_repository.dart';
|
||||
import 'package:wger/providers/gallery_repository.dart';
|
||||
import 'package:wger/providers/ingredient_repository.dart';
|
||||
import 'package:wger/providers/measurement_repository.dart';
|
||||
import 'package:wger/providers/nutrition_notifier.dart';
|
||||
import 'package:wger/providers/nutrition_repository.dart';
|
||||
import 'package:wger/providers/routines_notifier.dart';
|
||||
import 'package:wger/providers/user_profile_repository.dart';
|
||||
import 'package:wger/screens/home_tabs_screen.dart';
|
||||
import 'package:wger/theme/theme.dart';
|
||||
|
||||
import '../test/exercises/contribute_exercise_test.mocks.dart';
|
||||
import '../test/gallery/gallery_form_test.mocks.dart';
|
||||
import '../test/measurements/measurement_categories_screen_test.mocks.dart';
|
||||
import '../test/nutrition/nutritional_plan_screen_test.mocks.dart';
|
||||
import '../test/routine/weight_unit_form_widget_test.mocks.dart';
|
||||
import '../test/weight/weight_screen_test.mocks.dart' as weight;
|
||||
import '../test_data/body_weight.dart';
|
||||
import '../test_data/exercises.dart';
|
||||
import '../test_data/gallery.dart';
|
||||
import '../test_data/measurements.dart';
|
||||
import '../test_data/nutritional_plans.dart';
|
||||
import '../test_data/profile.dart';
|
||||
import '../test_data/routines.dart';
|
||||
|
||||
class _FakeAuthNotifier extends AuthNotifier {
|
||||
_FakeAuthNotifier(this._state);
|
||||
|
||||
final AuthState _state;
|
||||
|
||||
@override
|
||||
Future<AuthState> build() async => _state;
|
||||
}
|
||||
|
||||
Widget createDashboardScreen({Locale? locale}) {
|
||||
locale ??= const Locale('en');
|
||||
|
||||
final mockGalleryProvider = MockGalleryProvider();
|
||||
final mockGalleryRepo = MockGalleryRepository();
|
||||
when(mockGalleryRepo.watchAllDrift()).thenAnswer((_) => Stream.value(getTestImages()));
|
||||
|
||||
final mockExercisesProvider = MockExercisesProvider();
|
||||
final mockNutritionRepo = weight.MockNutritionRepository();
|
||||
final mockIngredientRepo = weight.MockIngredientRepository();
|
||||
when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null);
|
||||
|
||||
final mockAuthProvider = MockAuthProvider();
|
||||
when(mockAuthProvider.setServerVersion()).thenAnswer((_) async {});
|
||||
when(mockAuthProvider.dataInit).thenReturn(true);
|
||||
|
||||
final mockWorkoutProvider = MockRoutinesProvider();
|
||||
when(mockWorkoutProvider.items).thenReturn([getTestRoutine(exercises: getScreenshotExercises())]);
|
||||
final mockBodyWeightRepository = MockBodyWeightRepository();
|
||||
when(
|
||||
mockWorkoutProvider.currentRoutine,
|
||||
).thenReturn(getTestRoutine(exercises: getScreenshotExercises()));
|
||||
mockBodyWeightRepository.watchAllDrift(),
|
||||
).thenAnswer((_) => Stream.value(getWeightEntries()));
|
||||
|
||||
when(mockWorkoutProvider.fetchSessionData()).thenAnswer(
|
||||
(a) => Future.value([
|
||||
WorkoutSession(
|
||||
routineId: 1,
|
||||
date: DateTime.now().add(const Duration(days: -1)),
|
||||
timeStart: const TimeOfDay(hour: 17, minute: 34),
|
||||
timeEnd: const TimeOfDay(hour: 19, minute: 3),
|
||||
impression: 3,
|
||||
),
|
||||
]),
|
||||
final mockMeasurementRepo = MockMeasurementRepository();
|
||||
when(
|
||||
mockMeasurementRepo.watchAll(),
|
||||
).thenAnswer((_) => Stream<List<MeasurementCategory>>.value(getMeasurementCategories()));
|
||||
|
||||
final mockUserProfileRepo = weight.MockUserProfileRepository();
|
||||
when(
|
||||
mockUserProfileRepo.watchDrift(),
|
||||
).thenAnswer((_) => Stream.value(tUserProfile1));
|
||||
|
||||
const loggedInAuth = AuthState(
|
||||
status: AuthStatus.loggedIn,
|
||||
credential: LegacyCredential('test-token'),
|
||||
serverUrl: 'http://localhost',
|
||||
);
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository),
|
||||
measurementRepositoryProvider.overrideWithValue(mockMeasurementRepo),
|
||||
authProvider.overrideWith(() => _FakeAuthNotifier(loggedInAuth)),
|
||||
userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepo),
|
||||
nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo),
|
||||
ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo),
|
||||
galleryRepositoryProvider.overrideWithValue(mockGalleryRepo),
|
||||
],
|
||||
);
|
||||
container.read(routinesRiverpodProvider.notifier).state = AsyncData(
|
||||
RoutinesState(
|
||||
routines: [getTestRoutine(exercises: getScreenshotExercises())],
|
||||
),
|
||||
);
|
||||
|
||||
final mockNutritionProvider = weight.MockNutritionPlansProvider();
|
||||
// Seed the nutrition notifier with the screenshot plan so the dashboard can
|
||||
// show it without going through the server.
|
||||
container.read(nutritionProvider.notifier).state = AsyncData(
|
||||
NutritionState(plans: [getNutritionalPlanScreenshot()]),
|
||||
);
|
||||
|
||||
when(
|
||||
mockNutritionProvider.currentPlan,
|
||||
).thenAnswer((realInvocation) => getNutritionalPlanScreenshot());
|
||||
when(mockNutritionProvider.items).thenReturn([getNutritionalPlanScreenshot()]);
|
||||
|
||||
final mockWeightProvider = weight.MockBodyWeightProvider();
|
||||
when(mockWeightProvider.items).thenReturn(getScreenshotWeightEntries());
|
||||
|
||||
final mockMeasurementProvider = MockMeasurementProvider();
|
||||
when(mockMeasurementProvider.categories).thenReturn(getMeasurementCategories());
|
||||
|
||||
final mockUserProvider = MockUserProvider();
|
||||
when(mockUserProvider.profile).thenReturn(tProfile1);
|
||||
when(mockUserProvider.dashboardWidgets).thenReturn([
|
||||
DashboardWidget.routines,
|
||||
DashboardWidget.weight,
|
||||
DashboardWidget.measurements,
|
||||
DashboardWidget.calendar,
|
||||
DashboardWidget.nutrition,
|
||||
DashboardWidget.trophies,
|
||||
]);
|
||||
|
||||
return riverpod.ProviderScope(
|
||||
child: MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first)
|
||||
.copyWith(
|
||||
padding: EdgeInsets.zero,
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<GalleryProvider>(
|
||||
create: (context) => mockGalleryProvider,
|
||||
),
|
||||
ChangeNotifierProvider<ExercisesProvider>(
|
||||
create: (context) => mockExercisesProvider,
|
||||
),
|
||||
ChangeNotifierProvider<AuthProvider>(
|
||||
create: (context) => mockAuthProvider,
|
||||
),
|
||||
ChangeNotifierProvider<UserProvider>(
|
||||
create: (context) => mockUserProvider,
|
||||
),
|
||||
ChangeNotifierProvider<RoutinesProvider>(
|
||||
create: (context) => mockWorkoutProvider,
|
||||
),
|
||||
ChangeNotifierProvider<NutritionPlansProvider>(
|
||||
create: (context) => mockNutritionProvider,
|
||||
),
|
||||
ChangeNotifierProvider<BodyWeightProvider>(
|
||||
create: (context) => mockWeightProvider,
|
||||
),
|
||||
ChangeNotifierProvider<MeasurementProvider>(
|
||||
create: (context) => mockMeasurementProvider,
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: wgerLightTheme,
|
||||
home: HomeTabsScreen(),
|
||||
),
|
||||
return MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith(
|
||||
padding: EdgeInsets.zero,
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: wgerLightTheme,
|
||||
home: HomeTabsScreen(),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -17,14 +17,12 @@
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod;
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/providers/routines.dart';
|
||||
import 'package:wger/providers/routines_notifier.dart';
|
||||
import 'package:wger/screens/routine_screen.dart';
|
||||
import 'package:wger/theme/theme.dart';
|
||||
|
||||
import '../test/routine/routine_form_test.mocks.dart';
|
||||
import '../test_data/exercises.dart';
|
||||
import '../test_data/routines.dart';
|
||||
|
||||
@@ -32,9 +30,13 @@ Widget createWorkoutDetailScreen({Locale? locale}) {
|
||||
locale ??= const Locale('en');
|
||||
final key = GlobalKey<NavigatorState>();
|
||||
|
||||
final mockRoutinesProvider = MockRoutinesProvider();
|
||||
final routine = getTestRoutine(exercises: getScreenshotExercises());
|
||||
when(mockRoutinesProvider.findById(1)).thenReturn(routine);
|
||||
final container = riverpod.ProviderContainer.test();
|
||||
container.read(routinesRiverpodProvider.notifier).state = riverpod.AsyncData(
|
||||
RoutinesState(
|
||||
routines: [getTestRoutine(exercises: getScreenshotExercises())],
|
||||
),
|
||||
);
|
||||
|
||||
return MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith(
|
||||
@@ -42,12 +44,8 @@ Widget createWorkoutDetailScreen({Locale? locale}) {
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<RoutinesProvider>(
|
||||
create: (context) => mockRoutinesProvider,
|
||||
),
|
||||
],
|
||||
child: riverpod.UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
|
||||
@@ -19,35 +19,46 @@
|
||||
import 'package:clock/clock.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod;
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/providers/exercises.dart';
|
||||
import 'package:wger/models/workouts/routine.dart';
|
||||
import 'package:wger/providers/exercise_filter_state.dart';
|
||||
import 'package:wger/providers/exercise_filters_notifier.dart';
|
||||
import 'package:wger/providers/gym_state.dart';
|
||||
import 'package:wger/providers/routines.dart';
|
||||
import 'package:wger/providers/wger_base_riverpod.dart';
|
||||
import 'package:wger/providers/gym_state_notifier.dart';
|
||||
import 'package:wger/providers/routines_notifier.dart';
|
||||
import 'package:wger/screens/gym_mode.dart';
|
||||
import 'package:wger/screens/routine_screen.dart';
|
||||
import 'package:wger/theme/theme.dart';
|
||||
import 'package:wger/widgets/routines/gym_mode/summary.dart';
|
||||
|
||||
import '../test/routine/gym_mode/gym_mode_test.mocks.dart';
|
||||
import '../test_data/exercises.dart';
|
||||
import '../test_data/routines.dart';
|
||||
|
||||
class _StubRoutinesRiverpod extends RoutinesRiverpod {
|
||||
_StubRoutinesRiverpod(this._routines);
|
||||
final List<Routine> _routines;
|
||||
|
||||
@override
|
||||
Stream<RoutinesState> build() => Stream.value(RoutinesState(routines: _routines));
|
||||
}
|
||||
|
||||
Widget createGymModeScreen({Locale? locale}) {
|
||||
locale ??= const Locale('en');
|
||||
final key = GlobalKey<NavigatorState>();
|
||||
final exercises = getTestExercises();
|
||||
|
||||
final routine = getTestRoutine(exercises: getScreenshotExercises());
|
||||
final mockRoutinesProvider = MockRoutinesProvider();
|
||||
final mockExerciseProvider = MockExercisesProvider();
|
||||
|
||||
when(mockRoutinesProvider.fetchAndSetRoutineFull(1)).thenAnswer((_) async => routine);
|
||||
when(mockRoutinesProvider.findById(1)).thenAnswer((_) => routine);
|
||||
|
||||
when(mockExerciseProvider.findExerciseById(1)).thenReturn(exercises[0]); // bench press
|
||||
when(mockExerciseProvider.findExerciseById(6)).thenReturn(exercises[5]); // side raises
|
||||
final container = riverpod.ProviderContainer.test(
|
||||
overrides: [
|
||||
exerciseListFiltersProvider.overrideWithValue(
|
||||
ExerciseFilterState(exercises: getTestExercises()),
|
||||
),
|
||||
],
|
||||
);
|
||||
container.read(routinesRiverpodProvider.notifier).state = riverpod.AsyncData(
|
||||
RoutinesState(
|
||||
routines: [getTestRoutine(exercises: getScreenshotExercises())],
|
||||
),
|
||||
);
|
||||
|
||||
return MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith(
|
||||
@@ -55,41 +66,29 @@ Widget createGymModeScreen({Locale? locale}) {
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: riverpod.ProviderScope(
|
||||
overrides: [
|
||||
wgerBaseProvider.overrideWithValue(MockWgerBaseProvider()),
|
||||
],
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<RoutinesProvider>(
|
||||
create: (context) => mockRoutinesProvider,
|
||||
),
|
||||
ChangeNotifierProvider<ExercisesProvider>(
|
||||
create: (context) => mockExerciseProvider,
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
navigatorKey: key,
|
||||
theme: wgerLightTheme,
|
||||
home: TextButton(
|
||||
onPressed: () => key.currentState!.push(
|
||||
MaterialPageRoute<void>(
|
||||
settings: RouteSettings(
|
||||
arguments: GymModeArguments(routine.id!, routine.days.first.id!, 1),
|
||||
),
|
||||
builder: (_) => const GymModeScreen(),
|
||||
child: riverpod.UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
navigatorKey: key,
|
||||
theme: wgerLightTheme,
|
||||
home: TextButton(
|
||||
onPressed: () => key.currentState!.push(
|
||||
MaterialPageRoute<void>(
|
||||
settings: RouteSettings(
|
||||
arguments: GymModeArguments(routine.id!, routine.days.first.id!, 1),
|
||||
),
|
||||
builder: (_) => const GymModeScreen(),
|
||||
),
|
||||
child: const SizedBox(),
|
||||
),
|
||||
routes: {
|
||||
RoutineScreen.routeName: (ctx) => const RoutineScreen(),
|
||||
},
|
||||
child: const SizedBox(),
|
||||
),
|
||||
routes: {
|
||||
RoutineScreen.routeName: (ctx) => const RoutineScreen(),
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -100,18 +99,11 @@ Widget createGymModeResultsScreen({String locale = 'en'}) {
|
||||
|
||||
final key = GlobalKey<NavigatorState>();
|
||||
final routine = getTestRoutine(exercises: getScreenshotExercises());
|
||||
routine.sessions.first.session.date = clock.now();
|
||||
|
||||
final mockRoutinesProvider = MockRoutinesProvider();
|
||||
final mockExerciseProvider = MockExercisesProvider();
|
||||
|
||||
when(mockRoutinesProvider.fetchAndSetRoutineFull(1)).thenAnswer((_) async => routine);
|
||||
when(mockRoutinesProvider.findById(1)).thenAnswer((_) => routine);
|
||||
routine.sessions.first.date = clock.now();
|
||||
|
||||
return riverpod.UncontrolledProviderScope(
|
||||
container: riverpod.ProviderContainer.test(
|
||||
overrides: [
|
||||
wgerBaseProvider.overrideWithValue(MockWgerBaseProvider()),
|
||||
gymStateProvider.overrideWithValue(
|
||||
GymModeState(
|
||||
routine: routine,
|
||||
@@ -121,31 +113,25 @@ Widget createGymModeResultsScreen({String locale = 'en'}) {
|
||||
showTimerPages: true,
|
||||
),
|
||||
),
|
||||
routinesRiverpodProvider.overrideWith(
|
||||
() => _StubRoutinesRiverpod([routine]),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<RoutinesProvider>(
|
||||
create: (context) => mockRoutinesProvider,
|
||||
),
|
||||
ChangeNotifierProvider<ExercisesProvider>(
|
||||
create: (context) => mockExerciseProvider,
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: Locale(locale),
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
navigatorKey: key,
|
||||
theme: wgerLightTheme,
|
||||
home: Scaffold(
|
||||
body: PageView(
|
||||
controller: controller,
|
||||
children: [
|
||||
WorkoutSummary(controller),
|
||||
],
|
||||
),
|
||||
|
||||
child: MaterialApp(
|
||||
locale: Locale(locale),
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
navigatorKey: key,
|
||||
theme: wgerLightTheme,
|
||||
home: Scaffold(
|
||||
body: PageView(
|
||||
controller: controller,
|
||||
children: [
|
||||
WorkoutSummary(controller),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -17,10 +17,11 @@
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/providers/measurement.dart';
|
||||
import 'package:wger/models/measurements/measurement_category.dart';
|
||||
import 'package:wger/providers/measurement_repository.dart';
|
||||
import 'package:wger/screens/measurement_categories_screen.dart';
|
||||
import 'package:wger/theme/theme.dart';
|
||||
|
||||
@@ -30,8 +31,16 @@ import '../test_data/measurements.dart';
|
||||
Widget createMeasurementScreen({Locale? locale}) {
|
||||
locale ??= const Locale('en');
|
||||
|
||||
final mockMeasurementProvider = MockMeasurementProvider();
|
||||
when(mockMeasurementProvider.categories).thenReturn(getMeasurementCategories());
|
||||
final mockMeasurementRepo = MockMeasurementRepository();
|
||||
when(
|
||||
mockMeasurementRepo.watchAll(),
|
||||
).thenAnswer((_) => Stream<List<MeasurementCategory>>.value(getMeasurementCategories()));
|
||||
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
measurementRepositoryProvider.overrideWithValue(mockMeasurementRepo),
|
||||
],
|
||||
);
|
||||
|
||||
return MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith(
|
||||
@@ -39,12 +48,8 @@ Widget createMeasurementScreen({Locale? locale}) {
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<MeasurementProvider>(
|
||||
create: (context) => mockMeasurementProvider,
|
||||
),
|
||||
],
|
||||
child: UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
|
||||
@@ -16,43 +16,46 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wger/database/ingredients/ingredients_database.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/providers/body_weight.dart';
|
||||
import 'package:wger/providers/nutrition.dart';
|
||||
import 'package:wger/providers/body_weight_repository.dart';
|
||||
import 'package:wger/providers/ingredient_repository.dart';
|
||||
import 'package:wger/providers/nutrition_repository.dart';
|
||||
import 'package:wger/screens/nutritional_plan_screen.dart';
|
||||
import 'package:wger/theme/theme.dart';
|
||||
|
||||
import '../test/user/provider_test.mocks.dart';
|
||||
import '../test/nutrition/nutrition_provider_test.mocks.dart';
|
||||
import '../test/weight/weight_provider_test.mocks.dart';
|
||||
import '../test_data/body_weight.dart';
|
||||
import '../test_data/nutritional_plans.dart';
|
||||
|
||||
Widget createNutritionalPlanScreen({Locale? locale}) {
|
||||
locale ??= const Locale('en');
|
||||
final mockBaseProvider = MockWgerBaseProvider();
|
||||
|
||||
final key = GlobalKey<NavigatorState>();
|
||||
|
||||
final mockNutritionRepo = MockNutritionRepository();
|
||||
final mockIngredientRepo = MockIngredientRepository();
|
||||
when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null);
|
||||
|
||||
final mockBodyWeightRepository = MockBodyWeightRepository();
|
||||
when(
|
||||
mockBodyWeightRepository.watchAllDrift(),
|
||||
).thenAnswer((_) => Stream.value(getWeightEntries()));
|
||||
|
||||
return MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith(
|
||||
padding: EdgeInsets.zero,
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<NutritionPlansProvider>(
|
||||
create: (context) => NutritionPlansProvider(
|
||||
mockBaseProvider,
|
||||
[],
|
||||
database: IngredientDatabase.inMemory(NativeDatabase.memory()),
|
||||
),
|
||||
),
|
||||
ChangeNotifierProvider<BodyWeightProvider>(
|
||||
create: (context) => BodyWeightProvider(mockBaseProvider),
|
||||
),
|
||||
child: ProviderScope(
|
||||
overrides: [
|
||||
bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository),
|
||||
nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo),
|
||||
ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
|
||||
@@ -17,17 +17,18 @@
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:mockito/mockito.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/providers/body_weight.dart';
|
||||
import 'package:wger/providers/nutrition.dart';
|
||||
import 'package:wger/providers/user.dart';
|
||||
import 'package:wger/providers/body_weight_repository.dart';
|
||||
import 'package:wger/providers/ingredient_repository.dart';
|
||||
import 'package:wger/providers/nutrition_notifier.dart';
|
||||
import 'package:wger/providers/nutrition_repository.dart';
|
||||
import 'package:wger/providers/user_profile_repository.dart';
|
||||
import 'package:wger/screens/form_screen.dart';
|
||||
import 'package:wger/screens/weight_screen.dart';
|
||||
import 'package:wger/theme/theme.dart';
|
||||
|
||||
import '../test/utils.dart';
|
||||
import '../test/weight/weight_screen_test.mocks.dart';
|
||||
import '../test_data/body_weight.dart';
|
||||
import '../test_data/nutritional_plans.dart';
|
||||
@@ -35,15 +36,32 @@ import '../test_data/profile.dart';
|
||||
|
||||
Widget createWeightScreen({Locale? locale}) {
|
||||
locale ??= const Locale('en');
|
||||
final weightProvider = BodyWeightProvider(mockBaseProvider);
|
||||
weightProvider.items = getScreenshotWeightEntries();
|
||||
final mockBodyWeightRepository = MockBodyWeightRepository();
|
||||
when(
|
||||
mockBodyWeightRepository.watchAllDrift(),
|
||||
).thenAnswer((_) => Stream.value(getWeightEntries()));
|
||||
|
||||
final mockUserProvider = MockUserProvider();
|
||||
when(mockUserProvider.profile).thenReturn(tProfile1);
|
||||
final mockUserProfileRepository = MockUserProfileRepository();
|
||||
when(
|
||||
mockUserProfileRepository.watchDrift(),
|
||||
).thenAnswer((_) => Stream.value(tUserProfile1));
|
||||
|
||||
final mockNutritionPlansProvider = MockNutritionPlansProvider();
|
||||
when(mockNutritionPlansProvider.currentPlan).thenReturn(null);
|
||||
when(mockNutritionPlansProvider.items).thenReturn([getNutritionalPlan()]);
|
||||
final mockNutritionRepo = MockNutritionRepository();
|
||||
final mockIngredientRepo = MockIngredientRepository();
|
||||
when(mockIngredientRepo.getById(any)).thenAnswer((_) async => null);
|
||||
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
bodyWeightRepositoryProvider.overrideWithValue(mockBodyWeightRepository),
|
||||
userProfileRepositoryProvider.overrideWithValue(mockUserProfileRepository),
|
||||
nutritionRepositoryProvider.overrideWithValue(mockNutritionRepo),
|
||||
ingredientRepositoryProvider.overrideWithValue(mockIngredientRepo),
|
||||
],
|
||||
);
|
||||
// Seed the nutrition notifier with a plan so the weight overview can show it.
|
||||
container.read(nutritionProvider.notifier).state = AsyncData(
|
||||
NutritionState(plans: [getNutritionalPlan()]),
|
||||
);
|
||||
|
||||
return MediaQuery(
|
||||
data: MediaQueryData.fromView(WidgetsBinding.instance.platformDispatcher.views.first).copyWith(
|
||||
@@ -51,18 +69,8 @@ Widget createWeightScreen({Locale? locale}) {
|
||||
viewPadding: EdgeInsets.zero,
|
||||
viewInsets: EdgeInsets.zero,
|
||||
),
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider<UserProvider>(
|
||||
create: (context) => mockUserProvider,
|
||||
),
|
||||
ChangeNotifierProvider<BodyWeightProvider>(
|
||||
create: (context) => weightProvider,
|
||||
),
|
||||
ChangeNotifierProvider<NutritionPlansProvider>(
|
||||
create: (context) => mockNutritionPlansProvider,
|
||||
),
|
||||
],
|
||||
child: UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
locale: locale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
|
||||
3
ios/.gitignore
vendored
3
ios/.gitignore
vendored
@@ -10,7 +10,10 @@
|
||||
**/DerivedData/
|
||||
Icon?
|
||||
**/Pods/
|
||||
/Podfile
|
||||
/Podfile.lock
|
||||
**/.symlinks/
|
||||
**/Flutter/ephemeral/
|
||||
profile
|
||||
xcuserdata
|
||||
**/.generated/
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
|
||||
#include "Generated.xcconfig"
|
||||
|
||||
@@ -1,2 +1 @@
|
||||
#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
|
||||
#include "Generated.xcconfig"
|
||||
|
||||
45
ios/Podfile
45
ios/Podfile
@@ -1,45 +0,0 @@
|
||||
# Uncomment this line to define a global platform for your project
|
||||
platform :ios, '17.0'
|
||||
|
||||
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
|
||||
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
|
||||
|
||||
project 'Runner', {
|
||||
'Debug' => :debug,
|
||||
'Profile' => :release,
|
||||
'Release' => :release,
|
||||
}
|
||||
|
||||
def flutter_root
|
||||
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
|
||||
unless File.exist?(generated_xcode_build_settings_path)
|
||||
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
|
||||
end
|
||||
|
||||
File.foreach(generated_xcode_build_settings_path) do |line|
|
||||
matches = line.match(/FLUTTER_ROOT\=(.*)/)
|
||||
return matches[1].strip if matches
|
||||
end
|
||||
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
|
||||
end
|
||||
|
||||
require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)
|
||||
|
||||
flutter_ios_podfile_setup
|
||||
|
||||
target 'Runner' do
|
||||
use_frameworks!
|
||||
use_modular_headers!
|
||||
|
||||
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
|
||||
end
|
||||
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.each do |target|
|
||||
flutter_additional_ios_build_settings(target)
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['ENABLE_BITCODE'] = 'NO'
|
||||
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '16.0'
|
||||
end
|
||||
end
|
||||
end
|
||||
112
ios/Podfile.lock
112
ios/Podfile.lock
@@ -1,112 +0,0 @@
|
||||
PODS:
|
||||
- camera_avfoundation (0.0.1):
|
||||
- Flutter
|
||||
- Flutter (1.0.0)
|
||||
- flutter_native_splash (2.4.3):
|
||||
- Flutter
|
||||
- flutter_zxing (0.0.1):
|
||||
- Flutter
|
||||
- image_picker_ios (0.0.1):
|
||||
- Flutter
|
||||
- integration_test (0.0.1):
|
||||
- Flutter
|
||||
- package_info_plus (0.4.5):
|
||||
- Flutter
|
||||
- rive_common (0.0.1):
|
||||
- Flutter
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqlite3 (3.52.0):
|
||||
- sqlite3/common (= 3.52.0)
|
||||
- sqlite3/common (3.52.0)
|
||||
- sqlite3/dbstatvtab (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/fts5 (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/math (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/perf-threadsafe (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/rtree (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3/session (3.52.0):
|
||||
- sqlite3/common
|
||||
- sqlite3_flutter_libs (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- sqlite3 (~> 3.52.0)
|
||||
- sqlite3/dbstatvtab
|
||||
- sqlite3/fts5
|
||||
- sqlite3/math
|
||||
- sqlite3/perf-threadsafe
|
||||
- sqlite3/rtree
|
||||
- sqlite3/session
|
||||
- url_launcher_ios (0.0.1):
|
||||
- Flutter
|
||||
- video_player_avfoundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
|
||||
DEPENDENCIES:
|
||||
- camera_avfoundation (from `.symlinks/plugins/camera_avfoundation/ios`)
|
||||
- Flutter (from `Flutter`)
|
||||
- flutter_native_splash (from `.symlinks/plugins/flutter_native_splash/ios`)
|
||||
- flutter_zxing (from `.symlinks/plugins/flutter_zxing/ios`)
|
||||
- image_picker_ios (from `.symlinks/plugins/image_picker_ios/ios`)
|
||||
- integration_test (from `.symlinks/plugins/integration_test/ios`)
|
||||
- package_info_plus (from `.symlinks/plugins/package_info_plus/ios`)
|
||||
- rive_common (from `.symlinks/plugins/rive_common/ios`)
|
||||
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- sqlite3_flutter_libs (from `.symlinks/plugins/sqlite3_flutter_libs/darwin`)
|
||||
- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)
|
||||
- video_player_avfoundation (from `.symlinks/plugins/video_player_avfoundation/darwin`)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- sqlite3
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
camera_avfoundation:
|
||||
:path: ".symlinks/plugins/camera_avfoundation/ios"
|
||||
Flutter:
|
||||
:path: Flutter
|
||||
flutter_native_splash:
|
||||
:path: ".symlinks/plugins/flutter_native_splash/ios"
|
||||
flutter_zxing:
|
||||
:path: ".symlinks/plugins/flutter_zxing/ios"
|
||||
image_picker_ios:
|
||||
:path: ".symlinks/plugins/image_picker_ios/ios"
|
||||
integration_test:
|
||||
:path: ".symlinks/plugins/integration_test/ios"
|
||||
package_info_plus:
|
||||
:path: ".symlinks/plugins/package_info_plus/ios"
|
||||
rive_common:
|
||||
:path: ".symlinks/plugins/rive_common/ios"
|
||||
shared_preferences_foundation:
|
||||
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
|
||||
sqlite3_flutter_libs:
|
||||
:path: ".symlinks/plugins/sqlite3_flutter_libs/darwin"
|
||||
url_launcher_ios:
|
||||
:path: ".symlinks/plugins/url_launcher_ios/ios"
|
||||
video_player_avfoundation:
|
||||
:path: ".symlinks/plugins/video_player_avfoundation/darwin"
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
camera_avfoundation: 968a9a5323c79a99c166ad9d7866bfd2047b5a9b
|
||||
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
|
||||
flutter_native_splash: c32d145d68aeda5502d5f543ee38c192065986cf
|
||||
flutter_zxing: fe1338b6d79b8a455d209a28381e336b6cfb4161
|
||||
image_picker_ios: e0ece4aa2a75771a7de3fa735d26d90817041326
|
||||
integration_test: 4a889634ef21a45d28d50d622cf412dc6d9f586e
|
||||
package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
|
||||
rive_common: dd421daaf9ae69f0125aa761dd96abd278399952
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
sqlite3: a51c07cf16e023d6c48abd5e5791a61a47354921
|
||||
sqlite3_flutter_libs: b3e120efe9a82017e5552a620f696589ed4f62ab
|
||||
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
|
||||
video_player_avfoundation: dd410b52df6d2466a42d28550e33e4146928280a
|
||||
|
||||
PODFILE CHECKSUM: 140d612345f5f5eda8a7ae30f1ccf4e0b07aced5
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
@@ -8,9 +8,9 @@
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
|
||||
3845DFE0762714C6680D5DFA /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AFA44D9DB464FB85F130C5B5 /* Pods_Runner.framework */; };
|
||||
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
|
||||
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; };
|
||||
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
|
||||
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
|
||||
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
|
||||
@@ -30,14 +30,13 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
0ED96167FF623FAB319C6E99 /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
|
||||
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
|
||||
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
|
||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
|
||||
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = "<group>"; };
|
||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
|
||||
89F44165E15E0A7B109A05EB /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = "<group>"; };
|
||||
8D383D452D8E929100066A20 /* Runner.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Runner.entitlements; sourceTree = "<group>"; };
|
||||
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
|
||||
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
|
||||
@@ -46,8 +45,6 @@
|
||||
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
AFA44D9DB464FB85F130C5B5 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C71BAD15819A771165D784B0 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -55,24 +52,17 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
3845DFE0762714C6680D5DFA /* Pods_Runner.framework in Frameworks */,
|
||||
78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
23E168F95D2790D29E207E68 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
AFA44D9DB464FB85F130C5B5 /* Pods_Runner.framework */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
9740EEB11CF90186004384FC /* Flutter */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */,
|
||||
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
|
||||
9740EEB21CF90195004384FC /* Debug.xcconfig */,
|
||||
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
|
||||
@@ -88,7 +78,6 @@
|
||||
97C146F01CF9000F007C117D /* Runner */,
|
||||
97C146EF1CF9000F007C117D /* Products */,
|
||||
BB0286322FD60C00014F981C /* Pods */,
|
||||
23E168F95D2790D29E207E68 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -119,9 +108,6 @@
|
||||
BB0286322FD60C00014F981C /* Pods */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C71BAD15819A771165D784B0 /* Pods-Runner.debug.xcconfig */,
|
||||
0ED96167FF623FAB319C6E99 /* Pods-Runner.release.xcconfig */,
|
||||
89F44165E15E0A7B109A05EB /* Pods-Runner.profile.xcconfig */,
|
||||
);
|
||||
path = Pods;
|
||||
sourceTree = "<group>";
|
||||
@@ -133,20 +119,21 @@
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
|
||||
buildPhases = (
|
||||
49A79EC3F389C902853B9186 /* [CP] Check Pods Manifest.lock */,
|
||||
9740EEB61CF901F6004384FC /* Run Script */,
|
||||
97C146EA1CF9000F007C117D /* Sources */,
|
||||
97C146EB1CF9000F007C117D /* Frameworks */,
|
||||
97C146EC1CF9000F007C117D /* Resources */,
|
||||
9705A1C41CF9048500538489 /* Embed Frameworks */,
|
||||
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
|
||||
0A9E38C31DF3DC192213822E /* [CP] Embed Pods Frameworks */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = Runner;
|
||||
packageProductDependencies = (
|
||||
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */,
|
||||
);
|
||||
productName = Runner;
|
||||
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
@@ -175,6 +162,9 @@
|
||||
Base,
|
||||
);
|
||||
mainGroup = 97C146E51CF9000F007C117D;
|
||||
packageReferences = (
|
||||
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */,
|
||||
);
|
||||
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
@@ -199,23 +189,6 @@
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
0A9E38C31DF3DC192213822E /* [CP] Embed Pods Frameworks */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputFileListPaths = (
|
||||
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
|
||||
);
|
||||
name = "[CP] Embed Pods Frameworks";
|
||||
outputFileListPaths = (
|
||||
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
@@ -232,28 +205,6 @@
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
|
||||
};
|
||||
49A79EC3F389C902853B9186 /* [CP] Check Pods Manifest.lock */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputFileListPaths = (
|
||||
);
|
||||
inputPaths = (
|
||||
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
|
||||
"${PODS_ROOT}/Manifest.lock",
|
||||
);
|
||||
name = "[CP] Check Pods Manifest.lock";
|
||||
outputFileListPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
|
||||
showEnvVarsInLog = 0;
|
||||
};
|
||||
9740EEB61CF901F6004384FC /* Run Script */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
@@ -581,6 +532,20 @@
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = {
|
||||
isa = XCLocalSwiftPackageReference;
|
||||
relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage;
|
||||
};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = {
|
||||
isa = XCSwiftPackageProductDependency;
|
||||
productName = FlutterGeneratedPluginSwiftPackage;
|
||||
};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
};
|
||||
rootObject = 97C146E61CF9000F007C117D /* Project object */;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,24 @@
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<PreActions>
|
||||
<ExecutionAction
|
||||
ActionType = "Xcode.IDEStandardExecutionActionsCore.ExecutionActionType.ShellScriptAction">
|
||||
<ActionContent
|
||||
title = "Run Prepare Flutter Framework Script"
|
||||
scriptText = "/bin/sh "$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh" prepare ">
|
||||
<EnvironmentBuildable>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
|
||||
BuildableName = "Runner.app"
|
||||
BlueprintName = "Runner"
|
||||
ReferencedContainer = "container:Runner.xcodeproj">
|
||||
</BuildableReference>
|
||||
</EnvironmentBuildable>
|
||||
</ActionContent>
|
||||
</ExecutionAction>
|
||||
</PreActions>
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
|
||||
3
ios/Runner.xcworkspace/contents.xcworkspacedata
generated
3
ios/Runner.xcworkspace/contents.xcworkspacedata
generated
@@ -4,7 +4,4 @@
|
||||
<FileRef
|
||||
location = "group:Runner.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Pods/Pods.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
|
||||
@@ -61,6 +61,19 @@
|
||||
<string>$(FLUTTER_BUILD_NAME)</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>de.wger.flutter.app-auth</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Editor</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>wger</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(FLUTTER_BUILD_NUMBER)</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
|
||||
454
lib/core/error_dialogs.dart
Normal file
454
lib/core/error_dialogs.dart
Normal file
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_html/flutter_html.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:wger/core/exceptions/http_exception.dart';
|
||||
import 'package:wger/core/keys.dart';
|
||||
import 'package:wger/helpers/errors.dart';
|
||||
import 'package:wger/helpers/logs.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
/// Whether an error dialog is currently on screen.
|
||||
///
|
||||
/// Errors can fire in quick succession; this guards against stacking several
|
||||
/// modal dialogs on top of each other.
|
||||
bool _errorDialogVisible = false;
|
||||
|
||||
void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? context}) {
|
||||
final logger = Logger('showHttpExceptionErrorDialog');
|
||||
|
||||
// Attempt to get the BuildContext from our global navigatorKey.
|
||||
// This allows us to show a dialog even if the error occurs outside
|
||||
// of a widget's build method.
|
||||
final BuildContext? dialogContext = context ?? navigatorKey.currentContext;
|
||||
|
||||
if (dialogContext == null) {
|
||||
if (kDebugMode) {
|
||||
logger.warning('Error: Could not error show http error dialog because the context is null.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_errorDialogVisible) {
|
||||
logger.info('Suppressing error dialog, one is already visible: $exception');
|
||||
return;
|
||||
}
|
||||
_errorDialogVisible = true;
|
||||
|
||||
showDialog(
|
||||
context: dialogContext,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(AppLocalizations.of(ctx).anErrorOccurred),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (exception.type == ErrorType.html)
|
||||
ServerHtmlError(data: exception.htmlError)
|
||||
else
|
||||
...formatApiErrors(extractErrors(exception.errors)),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: Text(MaterialLocalizations.of(ctx).closeButtonLabel),
|
||||
onPressed: () {
|
||||
Navigator.of(ctx).pop();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
).whenComplete(() => _errorDialogVisible = false);
|
||||
}
|
||||
|
||||
/// Flattens a [WgerHttpException]'s context and error map into a readable
|
||||
/// multi-line string for the diagnostic dialog and bug report.
|
||||
String _formatHttpExceptionDetail(WgerHttpException error) {
|
||||
String lines(Map<String, dynamic> m) => m.entries.map((e) => '${e.key}: ${e.value}').join('\n');
|
||||
final ctx = error.context == null || error.context!.isEmpty ? '' : '${lines(error.context!)}\n\n';
|
||||
return '$ctx${lines(error.errors)}';
|
||||
}
|
||||
|
||||
void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext? context}) {
|
||||
// Attempt to get the BuildContext from our global navigatorKey.
|
||||
// This allows us to show a dialog even if the error occurs outside
|
||||
// of a widget's build method.
|
||||
final BuildContext? dialogContext = context ?? navigatorKey.currentContext;
|
||||
|
||||
final logger = Logger('showGeneralErrorDialog');
|
||||
|
||||
if (dialogContext == null) {
|
||||
if (kDebugMode) {
|
||||
logger.warning('Error: Could not error show dialog because the context is null.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_errorDialogVisible) {
|
||||
logger.info('Suppressing error dialog, one is already visible: $error');
|
||||
return;
|
||||
}
|
||||
_errorDialogVisible = true;
|
||||
|
||||
final i18n = AppLocalizations.of(dialogContext);
|
||||
|
||||
// If possible, determine the issue title and message based on the error type.
|
||||
// (Note that issue titles and error messages are not localized)
|
||||
String issueTitle = 'An error occurred';
|
||||
String issueErrorMessage = error.toString();
|
||||
|
||||
if (error is FlutterErrorDetails) {
|
||||
issueTitle = 'Application Error';
|
||||
issueErrorMessage = error.exceptionAsString();
|
||||
} else if (error is MissingRequiredKeysException) {
|
||||
issueTitle = 'Missing Required Key';
|
||||
} else if (error is WgerHttpException) {
|
||||
final status = error.statusCode == null ? '' : ' (HTTP ${error.statusCode})';
|
||||
issueTitle = switch (error.source) {
|
||||
ExceptionSource.powersync => 'Sync upload rejected$status',
|
||||
ExceptionSource.flutter => 'Application error$status',
|
||||
ExceptionSource.api => 'Server error$status',
|
||||
};
|
||||
issueErrorMessage = _formatHttpExceptionDetail(error);
|
||||
}
|
||||
|
||||
final String fullStackTrace = stackTrace?.toString() ?? 'No stack trace available.';
|
||||
final applicationLogs = InMemoryLogStore().getFormattedLogs();
|
||||
|
||||
showDialog(
|
||||
context: dialogContext,
|
||||
barrierDismissible: false,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Row(
|
||||
spacing: 8,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error, color: Theme.of(context).colorScheme.error),
|
||||
Expanded(
|
||||
child: Text(
|
||||
i18n.anErrorOccurred,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SingleChildScrollView(
|
||||
child: ListBody(
|
||||
children: [
|
||||
Text(i18n.errorInfoDescription),
|
||||
const SizedBox(height: 8),
|
||||
Text(i18n.errorInfoDescription2),
|
||||
const SizedBox(height: 10),
|
||||
ExpansionTile(
|
||||
tilePadding: EdgeInsets.zero,
|
||||
title: Text(i18n.errorViewDetails),
|
||||
children: [
|
||||
Text(
|
||||
issueErrorMessage,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Container(
|
||||
alignment: Alignment.topLeft,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
constraints: const BoxConstraints(maxHeight: 250),
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
fullStackTrace,
|
||||
style: TextStyle(fontSize: 12.0, color: Colors.grey[700]),
|
||||
),
|
||||
),
|
||||
),
|
||||
CopyToClipboardButton(
|
||||
text:
|
||||
'Error Title: $issueTitle\n'
|
||||
'Error Message: $issueErrorMessage\n\n'
|
||||
'Stack Trace:\n$fullStackTrace',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(i18n.applicationLogs, style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
Container(
|
||||
alignment: Alignment.topLeft,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
constraints: const BoxConstraints(maxHeight: 250),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
...applicationLogs.map(
|
||||
(entry) => Text(
|
||||
entry,
|
||||
style: TextStyle(fontSize: 12.0, color: Colors.grey[700]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
CopyToClipboardButton(text: applicationLogs.join('\n')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: const Text('Report issue'),
|
||||
onPressed: () async {
|
||||
final githubIssueUrl = buildGithubIssueUrl(
|
||||
issueTitle: issueTitle,
|
||||
issueErrorMessage: issueErrorMessage,
|
||||
stackTrace: fullStackTrace,
|
||||
applicationLogs: applicationLogs,
|
||||
);
|
||||
final Uri reportUri = Uri.parse(githubIssueUrl);
|
||||
|
||||
try {
|
||||
await launchUrl(reportUri, mode: LaunchMode.externalApplication);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
logger.warning('Error launching URL: $e');
|
||||
}
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Error opening issue tracker: $e')));
|
||||
}
|
||||
},
|
||||
),
|
||||
FilledButton(
|
||||
child: Text(MaterialLocalizations.of(context).okButtonLabel),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
).whenComplete(() => _errorDialogVisible = false);
|
||||
}
|
||||
|
||||
/// Routes [error] to the appropriate UI based on its [ErrorSeverity].
|
||||
///
|
||||
/// The caller is responsible for logging the error beforehand.
|
||||
void handleError(Object? error, StackTrace? stackTrace) {
|
||||
switch (classifyError(error)) {
|
||||
case ErrorSeverity.cosmetic:
|
||||
break;
|
||||
case ErrorSeverity.transient:
|
||||
showTransientErrorSnackbar();
|
||||
case ErrorSeverity.fatal:
|
||||
// API errors are the form-validation fallback (clean field errors);
|
||||
// other sources are diagnostic and get the dialog with logs and report.
|
||||
if (error is WgerHttpException && error.source == ExceptionSource.api) {
|
||||
showHttpExceptionErrorDialog(error);
|
||||
} else {
|
||||
showGeneralErrorDialog(error, stackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a brief, non-blocking snackbar telling the user about a (hopefully)
|
||||
/// transient error such as network problems, etc.
|
||||
void showTransientErrorSnackbar() {
|
||||
final messenger = scaffoldMessengerKey.currentState;
|
||||
final context = navigatorKey.currentContext;
|
||||
|
||||
if (messenger == null || context == null) {
|
||||
if (kDebugMode) {
|
||||
Logger(
|
||||
'showNetworkErrorSnackbar',
|
||||
).warning('Could not show snackbar: no messenger or context available.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
messenger
|
||||
..clearSnackBars()
|
||||
..showSnackBar(
|
||||
SnackBar(content: Text(AppLocalizations.of(context).errorCouldNotConnectToServer)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Shows a brief, non-blocking snackbar telling the user their session is no
|
||||
/// longer valid and they need to log in again.
|
||||
void showSessionExpiredSnackbar() {
|
||||
final messenger = scaffoldMessengerKey.currentState;
|
||||
final context = navigatorKey.currentContext;
|
||||
|
||||
if (messenger == null || context == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
messenger
|
||||
..clearSnackBars()
|
||||
..showSnackBar(
|
||||
SnackBar(content: Text(AppLocalizations.of(context).sessionExpired)),
|
||||
);
|
||||
}
|
||||
|
||||
/// A widget to render HTML errors returned by the server
|
||||
///
|
||||
/// This is a simple wrapper around the `Html` Widget, with some light changes
|
||||
/// to the style.
|
||||
class ServerHtmlError extends StatelessWidget {
|
||||
final logger = Logger('ServerHtml');
|
||||
final String data;
|
||||
|
||||
ServerHtmlError({required this.data, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Html(
|
||||
data: data,
|
||||
style: {
|
||||
'h1': Style(fontSize: FontSize(theme.textTheme.bodyLarge?.fontSize ?? 15)),
|
||||
'h2': Style(fontSize: FontSize(theme.textTheme.bodyMedium?.fontSize ?? 15)),
|
||||
},
|
||||
doNotRenderTheseTags: const {'a'},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CopyToClipboardButton extends StatelessWidget {
|
||||
final logger = Logger('CopyToClipboardButton');
|
||||
final String text;
|
||||
|
||||
CopyToClipboardButton({required this.text, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final i18n = AppLocalizations.of(context);
|
||||
|
||||
return TextButton.icon(
|
||||
icon: const Icon(Icons.copy_all_outlined, size: 18),
|
||||
label: Text(i18n.copyToClipboard),
|
||||
style: TextButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: text))
|
||||
.then((_) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('Details copied to clipboard!')));
|
||||
}
|
||||
})
|
||||
.catchError((copyError) {
|
||||
logger.warning('Error copying to clipboard: $copyError');
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('Could not copy details.')));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Processes the error messages from the server and returns a list of widgets
|
||||
List<Widget> formatApiErrors(List<ApiError> errors, {Color? color}) {
|
||||
final logger = Logger('formatApiErrors');
|
||||
|
||||
final List<Widget> errorList = [];
|
||||
|
||||
for (final error in errors) {
|
||||
errorList.add(
|
||||
Text(
|
||||
error.key,
|
||||
style: TextStyle(fontWeight: FontWeight.bold, color: color),
|
||||
),
|
||||
);
|
||||
|
||||
logger.warning(error.errorMessages);
|
||||
for (final message in error.errorMessages) {
|
||||
errorList.add(Text(message, style: TextStyle(color: color)));
|
||||
}
|
||||
errorList.add(const SizedBox(height: 8));
|
||||
}
|
||||
|
||||
return errorList;
|
||||
}
|
||||
|
||||
/// Processes the error messages from the server and returns a list of widgets
|
||||
List<Widget> formatTextErrors(List<String> errors, {String? title, Color? color}) {
|
||||
final List<Widget> errorList = [];
|
||||
|
||||
// A null color inherits the surrounding text style (readable in dark mode).
|
||||
if (title != null) {
|
||||
errorList.add(
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(fontWeight: FontWeight.bold, color: color),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (final message in errors) {
|
||||
errorList.add(Text(message, style: TextStyle(color: color)));
|
||||
}
|
||||
errorList.add(const SizedBox(height: 8));
|
||||
|
||||
return errorList;
|
||||
}
|
||||
|
||||
class FormHttpErrorsWidget extends StatelessWidget {
|
||||
final WgerHttpException exception;
|
||||
|
||||
const FormHttpErrorsWidget(this.exception, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Container(
|
||||
constraints: const BoxConstraints(maxHeight: 250),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: theme.colorScheme.error, width: 1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: theme.colorScheme.error),
|
||||
if (exception.type == ErrorType.html)
|
||||
ServerHtmlError(data: exception.htmlError)
|
||||
else
|
||||
...formatApiErrors(
|
||||
extractErrors(exception.errors),
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,11 @@ enum ErrorType {
|
||||
text,
|
||||
}
|
||||
|
||||
/// Where an exception originated, so the error handler can route and present
|
||||
/// it differently (a plain API validation error vs a PowerSync upload
|
||||
/// rejection worth reporting).
|
||||
enum ExceptionSource { api, powersync, flutter }
|
||||
|
||||
const HTML_ERROR_KEY = 'html_error';
|
||||
|
||||
class WgerHttpException implements Exception {
|
||||
@@ -37,8 +42,21 @@ class WgerHttpException implements Exception {
|
||||
/// or similar.
|
||||
late ErrorType type;
|
||||
|
||||
/// Where the exception came from (drives routing and presentation).
|
||||
final ExceptionSource source;
|
||||
|
||||
/// The HTTP status code, when built from a [Response].
|
||||
final int? statusCode;
|
||||
|
||||
/// Optional structured context for diagnostics (e.g. the PowerSync table/op).
|
||||
final Map<String, dynamic>? context;
|
||||
|
||||
/// Custom http exception
|
||||
WgerHttpException(Response response) {
|
||||
WgerHttpException(
|
||||
Response response, {
|
||||
this.source = ExceptionSource.api,
|
||||
this.context,
|
||||
}) : statusCode = response.statusCode {
|
||||
type = ErrorType.json;
|
||||
final dynamic responseBody = response.body;
|
||||
|
||||
@@ -67,7 +85,12 @@ class WgerHttpException implements Exception {
|
||||
}
|
||||
}
|
||||
|
||||
WgerHttpException.fromMap(Map<String, dynamic> map) : type = ErrorType.json {
|
||||
WgerHttpException.fromMap(
|
||||
Map<String, dynamic> map, {
|
||||
this.source = ExceptionSource.api,
|
||||
this.statusCode,
|
||||
this.context,
|
||||
}) : type = ErrorType.json {
|
||||
errors = map;
|
||||
}
|
||||
|
||||
@@ -81,6 +104,7 @@ class WgerHttpException implements Exception {
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'WgerHttpException ($type): $errors';
|
||||
final ctxStr = context == null ? '' : ', context: $context';
|
||||
return 'WgerHttpException(${source.name}, status ${statusCode ?? '-'}, $type): $errors$ctxStr';
|
||||
}
|
||||
}
|
||||
|
||||
35
lib/core/exceptions/mfa_required_exception.dart
Normal file
35
lib/core/exceptions/mfa_required_exception.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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
|
||||
* 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/>.
|
||||
*/
|
||||
|
||||
/// Thrown when an `allauth.headless` login or signup response indicates that
|
||||
/// the user must complete a second authentication factor before the session
|
||||
/// can be issued tokens.
|
||||
///
|
||||
/// The [sessionToken] carries the short-lived flow handle that the follow-up
|
||||
/// call to `auth/2fa/authenticate` must echo back. [availableFactors] lists
|
||||
/// the supported factor ids ('totp', 'recovery_codes', 'webauthn') when the
|
||||
/// server included them, so the UI can pick the right input affordance.
|
||||
class MfaRequiredException implements Exception {
|
||||
final String sessionToken;
|
||||
final List<String> availableFactors;
|
||||
|
||||
const MfaRequiredException({required this.sessionToken, this.availableFactors = const []});
|
||||
|
||||
@override
|
||||
String toString() => 'MfaRequiredException(factors: $availableFactors, sessionToken: <redacted>)';
|
||||
}
|
||||
27
lib/core/keys.dart
Normal file
27
lib/core/keys.dart
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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';
|
||||
|
||||
/// App-wide navigator key. Lets code outside the widget tree (the global error
|
||||
/// handlers, background callbacks) reach a [BuildContext] and the navigator.
|
||||
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
|
||||
/// App-wide scaffold-messenger key, for showing snackbars from outside the
|
||||
/// widget tree.
|
||||
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
|
||||
@@ -1,42 +0,0 @@
|
||||
import 'dart:developer';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:wger/database/exercises/exercise_database.dart';
|
||||
import 'package:wger/database/ingredients/ingredients_database.dart';
|
||||
|
||||
final locator = GetIt.asNewInstance();
|
||||
|
||||
class ServiceLocator {
|
||||
factory ServiceLocator() => _singleton;
|
||||
|
||||
const ServiceLocator._internal();
|
||||
|
||||
static const ServiceLocator _singleton = ServiceLocator._internal();
|
||||
|
||||
Future<void> _initDB() async {
|
||||
ExerciseDatabase exerciseDB;
|
||||
IngredientDatabase ingredientDB;
|
||||
|
||||
if (Platform.environment.containsKey('FLUTTER_TEST')) {
|
||||
exerciseDB = ExerciseDatabase.inMemory(NativeDatabase.memory());
|
||||
ingredientDB = IngredientDatabase.inMemory(NativeDatabase.memory());
|
||||
} else {
|
||||
exerciseDB = ExerciseDatabase();
|
||||
ingredientDB = IngredientDatabase();
|
||||
}
|
||||
|
||||
locator.registerSingleton<ExerciseDatabase>(exerciseDB);
|
||||
locator.registerSingleton<IngredientDatabase>(ingredientDB);
|
||||
}
|
||||
|
||||
Future<void> configure() async {
|
||||
try {
|
||||
await _initDB();
|
||||
} catch (e, _) {
|
||||
log(e.toString());
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,21 @@
|
||||
/*
|
||||
* 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:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
String? validateUrl(String? value, AppLocalizations i18n, {bool required = true}) {
|
||||
@@ -15,10 +33,12 @@ String? validateUrl(String? value, AppLocalizations i18n, {bool required = true}
|
||||
return i18n.invalidUrl;
|
||||
}
|
||||
|
||||
// Try to parse as URI
|
||||
// Try to parse as URI. The earlier startsWith check guarantees a scheme
|
||||
// and the `//` authority delimiter, but `Uri.parse('http://')` still
|
||||
// succeeds with an empty host which we reject explicitly
|
||||
try {
|
||||
final uri = Uri.parse(value);
|
||||
if (!uri.hasScheme || !uri.hasAuthority) {
|
||||
if (uri.host.isEmpty) {
|
||||
return i18n.invalidUrl;
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* 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
|
||||
@@ -26,7 +26,8 @@ class WidescreenWrapper extends StatelessWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
return Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: MATERIAL_MD_BREAKPOINT),
|
||||
child: child,
|
||||
|
||||
44
lib/database/converters/date_only_text_converter.dart
Normal file
44
lib/database/converters/date_only_text_converter.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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
|
||||
* 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:drift/drift.dart';
|
||||
|
||||
/// Persists a Django `DateField` (a calendar day, no time, no zone) as a
|
||||
/// `YYYY-MM-DD` string, the format the backend stores and syncs back. Without
|
||||
/// it drift would write the local day as a full ISO timestamp, so a row written
|
||||
/// here and the same row after a server round-trip would no longer compare
|
||||
/// equal. Reading takes the leading day, so timestamps written before this
|
||||
/// converter still map to the correct date.
|
||||
///
|
||||
/// Use only on columns backed by a Django `DateField`. For `DateTimeField`
|
||||
/// columns use `UtcDateTimeConverter` instead.
|
||||
class DateOnlyTextConverter extends TypeConverter<DateTime, String> {
|
||||
const DateOnlyTextConverter();
|
||||
|
||||
@override
|
||||
DateTime fromSql(String fromDb) {
|
||||
final day = DateTime.parse(fromDb.substring(0, 10));
|
||||
return DateTime.utc(day.year, day.month, day.day);
|
||||
}
|
||||
|
||||
@override
|
||||
String toSql(DateTime value) =>
|
||||
'${value.year.toString().padLeft(4, '0')}-'
|
||||
'${value.month.toString().padLeft(2, '0')}-'
|
||||
'${value.day.toString().padLeft(2, '0')}';
|
||||
}
|
||||
32
lib/database/converters/exercise_image_style_converter.dart
Normal file
32
lib/database/converters/exercise_image_style_converter.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:wger/models/exercises/image.dart';
|
||||
|
||||
/// Maps an [ExerciseImageStyle] to and from the Django wire format
|
||||
/// (`'1'`–`'5'`).
|
||||
class ExerciseImageStyleConverter extends TypeConverter<ExerciseImageStyle, String> {
|
||||
const ExerciseImageStyleConverter();
|
||||
|
||||
@override
|
||||
ExerciseImageStyle fromSql(String fromDb) => ExerciseImageStyle.fromWire(fromDb);
|
||||
|
||||
@override
|
||||
String toSql(ExerciseImageStyle value) => value.wireValue;
|
||||
}
|
||||
35
lib/database/converters/time_of_day_converter.dart
Normal file
35
lib/database/converters/time_of_day_converter.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (c) 2020, 2020- 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:drift/drift.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:wger/helpers/json.dart';
|
||||
|
||||
class TimeOfDayConverter extends TypeConverter<TimeOfDay, String> {
|
||||
const TimeOfDayConverter();
|
||||
|
||||
@override
|
||||
TimeOfDay fromSql(String fromDb) {
|
||||
return stringToTimeNull(fromDb)!;
|
||||
}
|
||||
|
||||
@override
|
||||
String toSql(TimeOfDay value) {
|
||||
return timeToString(value)!;
|
||||
}
|
||||
}
|
||||
35
lib/database/converters/utc_datetime_converter.dart
Normal file
35
lib/database/converters/utc_datetime_converter.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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
|
||||
* 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:drift/drift.dart';
|
||||
|
||||
/// Persists [DateTime] values as UTC and returns them in the device's local zone.
|
||||
///
|
||||
/// Use only on columns backed by a Django `DateTimeField`. Date-only
|
||||
/// (`DateField`) columns must not use it, or their calendar day would shift in
|
||||
/// zones west or east of UTC. The local conversion on read is required because
|
||||
/// both local writes and server sync store instants as UTC
|
||||
class UtcDateTimeConverter extends TypeConverter<DateTime, DateTime> {
|
||||
const UtcDateTimeConverter();
|
||||
|
||||
@override
|
||||
DateTime fromSql(DateTime fromDb) => fromDb.toLocal();
|
||||
|
||||
@override
|
||||
DateTime toSql(DateTime value) => value.toUtc();
|
||||
}
|
||||
32
lib/database/converters/workout_impression_converter.dart
Normal file
32
lib/database/converters/workout_impression_converter.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:wger/models/workouts/session.dart';
|
||||
|
||||
/// Maps a [WorkoutImpression] to and from the Django wire format
|
||||
/// (`'1'`, `'2'`, `'3'`).
|
||||
class WorkoutImpressionConverter extends TypeConverter<WorkoutImpression, String> {
|
||||
const WorkoutImpressionConverter();
|
||||
|
||||
@override
|
||||
WorkoutImpression fromSql(String fromDb) => WorkoutImpression.fromWire(fromDb);
|
||||
|
||||
@override
|
||||
String toSql(WorkoutImpression value) => value.wireValue;
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:drift_flutter/drift_flutter.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:wger/database/exercises/type_converters.dart';
|
||||
import 'package:wger/models/exercises/category.dart';
|
||||
import 'package:wger/models/exercises/equipment.dart';
|
||||
import 'package:wger/models/exercises/language.dart';
|
||||
import 'package:wger/models/exercises/muscle.dart';
|
||||
|
||||
part 'exercise_database.g.dart';
|
||||
|
||||
@DataClassName('ExerciseTable')
|
||||
class Exercises extends Table {
|
||||
const Exercises();
|
||||
|
||||
IntColumn get id => integer()();
|
||||
|
||||
TextColumn get data => text()();
|
||||
|
||||
// TextColumn get data => text().map(const ExerciseBaseConverter())();
|
||||
|
||||
DateTimeColumn get lastUpdate => dateTime()();
|
||||
|
||||
/// The date when the exercise was last fetched from the API. While we know
|
||||
/// when the exercise itself was last updated in `lastUpdate`, we can save
|
||||
/// ourselves a lot of requests if we don't check too often
|
||||
DateTimeColumn get lastFetched => dateTime()();
|
||||
}
|
||||
|
||||
@DataClassName('MuscleTable')
|
||||
class Muscles extends Table {
|
||||
const Muscles();
|
||||
|
||||
IntColumn get id => integer()();
|
||||
|
||||
TextColumn get data => text().map(const MuscleConverter())();
|
||||
}
|
||||
|
||||
@DataClassName('CategoryTable')
|
||||
class Categories extends Table {
|
||||
const Categories();
|
||||
|
||||
IntColumn get id => integer()();
|
||||
|
||||
TextColumn get data => text().map(const ExerciseCategoryConverter())();
|
||||
}
|
||||
|
||||
@DataClassName('LanguagesTable')
|
||||
class Languages extends Table {
|
||||
const Languages();
|
||||
|
||||
IntColumn get id => integer()();
|
||||
|
||||
TextColumn get data => text().map(const LanguageConverter())();
|
||||
}
|
||||
|
||||
@DataClassName('EquipmentTable')
|
||||
class Equipments extends Table {
|
||||
const Equipments();
|
||||
|
||||
IntColumn get id => integer()();
|
||||
|
||||
TextColumn get data => text().map(const EquipmentConverter())();
|
||||
}
|
||||
|
||||
@DriftDatabase(tables: [Exercises, Muscles, Equipments, Categories, Languages])
|
||||
class ExerciseDatabase extends _$ExerciseDatabase {
|
||||
final _logger = Logger('ExerciseDatabase');
|
||||
|
||||
ExerciseDatabase() : super(_openConnection());
|
||||
|
||||
// Named constructor for creating in-memory database
|
||||
ExerciseDatabase.inMemory(super.e);
|
||||
|
||||
/// Note that this needs to be bumped if the JSON response from the server changes
|
||||
@override
|
||||
int get schemaVersion => 4;
|
||||
|
||||
/// There is not really a migration strategy. If we bump the version
|
||||
/// number, delete everything and recreate the new tables. The provider
|
||||
/// will fetch everything as needed from the server
|
||||
@override
|
||||
MigrationStrategy get migration => MigrationStrategy(
|
||||
onUpgrade: (m, from, to) async {
|
||||
// no-op, but needs to be defined
|
||||
return;
|
||||
},
|
||||
beforeOpen: (openingDetails) async {
|
||||
if (openingDetails.hadUpgrade) {
|
||||
final m = createMigrator();
|
||||
for (final table in allTables) {
|
||||
await m.deleteTable(table.actualTableName);
|
||||
await m.createTable(table);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
Future<void> deleteEverything() {
|
||||
return transaction(() async {
|
||||
for (final table in allTables) {
|
||||
_logger.info('Deleting db cache table ${table.actualTableName}');
|
||||
await delete(table).go();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
QueryExecutor _openConnection() {
|
||||
return driftDatabase(name: 'exercises');
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,63 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:wger/models/exercises/category.dart';
|
||||
import 'package:wger/models/exercises/equipment.dart';
|
||||
import 'package:wger/models/exercises/language.dart';
|
||||
import 'package:wger/models/exercises/muscle.dart';
|
||||
|
||||
class MuscleConverter extends TypeConverter<Muscle, String> {
|
||||
const MuscleConverter();
|
||||
|
||||
@override
|
||||
Muscle fromSql(String fromDb) {
|
||||
return Muscle.fromJson(json.decode(fromDb) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
@override
|
||||
String toSql(Muscle value) {
|
||||
return json.encode(value.toJson());
|
||||
}
|
||||
}
|
||||
|
||||
class EquipmentConverter extends TypeConverter<Equipment, String> {
|
||||
const EquipmentConverter();
|
||||
|
||||
@override
|
||||
Equipment fromSql(String fromDb) {
|
||||
return Equipment.fromJson(json.decode(fromDb) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
@override
|
||||
String toSql(Equipment value) {
|
||||
return json.encode(value.toJson());
|
||||
}
|
||||
}
|
||||
|
||||
class ExerciseCategoryConverter extends TypeConverter<ExerciseCategory, String> {
|
||||
const ExerciseCategoryConverter();
|
||||
|
||||
@override
|
||||
ExerciseCategory fromSql(String fromDb) {
|
||||
return ExerciseCategory.fromJson(json.decode(fromDb) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
@override
|
||||
String toSql(ExerciseCategory value) {
|
||||
return json.encode(value.toJson());
|
||||
}
|
||||
}
|
||||
|
||||
class LanguageConverter extends TypeConverter<Language, String> {
|
||||
const LanguageConverter();
|
||||
|
||||
@override
|
||||
Language fromSql(String fromDb) {
|
||||
return Language.fromJson(json.decode(fromDb) as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
@override
|
||||
String toSql(Language value) {
|
||||
return json.encode(value.toJson());
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:drift_flutter/drift_flutter.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
part 'ingredients_database.g.dart';
|
||||
|
||||
@DataClassName('IngredientTable')
|
||||
class Ingredients extends Table {
|
||||
const Ingredients();
|
||||
|
||||
IntColumn get id => integer()();
|
||||
|
||||
TextColumn get data => text()();
|
||||
|
||||
/// The date when the ingredient was last fetched from the server
|
||||
DateTimeColumn get lastFetched => dateTime()();
|
||||
}
|
||||
|
||||
@DriftDatabase(tables: [Ingredients])
|
||||
class IngredientDatabase extends _$IngredientDatabase {
|
||||
final _logger = Logger('IngredientDatabase');
|
||||
|
||||
IngredientDatabase() : super(_openConnection());
|
||||
|
||||
// Named constructor for creating in-memory database
|
||||
IngredientDatabase.inMemory(super.e);
|
||||
|
||||
/// Note that this needs to be bumped if the JSON response from the server changes
|
||||
@override
|
||||
int get schemaVersion => 2;
|
||||
|
||||
/// There is not really a migration strategy. If we bump the version
|
||||
/// number, delete everything and recreate the new tables. The nutrition provider
|
||||
/// will fetch everything as needed from the server
|
||||
@override
|
||||
MigrationStrategy get migration => MigrationStrategy(
|
||||
onUpgrade: (m, from, to) async {
|
||||
// no-op, but needs to be defined
|
||||
return;
|
||||
},
|
||||
beforeOpen: (openingDetails) async {
|
||||
if (openingDetails.hadUpgrade) {
|
||||
final m = createMigrator();
|
||||
for (final table in allTables) {
|
||||
await m.deleteTable(table.actualTableName);
|
||||
await m.createTable(table);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
Future<void> deleteEverything() {
|
||||
return transaction(() async {
|
||||
for (final table in allTables) {
|
||||
_logger.info('Deleting db cache table ${table.actualTableName}');
|
||||
await delete(table).go();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
QueryExecutor _openConnection() {
|
||||
return driftDatabase(name: 'ingredients');
|
||||
}
|
||||
@@ -1,445 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'ingredients_database.dart';
|
||||
|
||||
// ignore_for_file: type=lint
|
||||
class $IngredientsTable extends Ingredients with TableInfo<$IngredientsTable, IngredientTable> {
|
||||
@override
|
||||
final GeneratedDatabase attachedDatabase;
|
||||
final String? _alias;
|
||||
$IngredientsTable(this.attachedDatabase, [this._alias]);
|
||||
static const VerificationMeta _idMeta = const VerificationMeta('id');
|
||||
@override
|
||||
late final GeneratedColumn<int> id = GeneratedColumn<int>(
|
||||
'id',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.int,
|
||||
requiredDuringInsert: true,
|
||||
);
|
||||
static const VerificationMeta _dataMeta = const VerificationMeta('data');
|
||||
@override
|
||||
late final GeneratedColumn<String> data = GeneratedColumn<String>(
|
||||
'data',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.string,
|
||||
requiredDuringInsert: true,
|
||||
);
|
||||
static const VerificationMeta _lastFetchedMeta = const VerificationMeta(
|
||||
'lastFetched',
|
||||
);
|
||||
@override
|
||||
late final GeneratedColumn<DateTime> lastFetched = GeneratedColumn<DateTime>(
|
||||
'last_fetched',
|
||||
aliasedName,
|
||||
false,
|
||||
type: DriftSqlType.dateTime,
|
||||
requiredDuringInsert: true,
|
||||
);
|
||||
@override
|
||||
List<GeneratedColumn> get $columns => [id, data, lastFetched];
|
||||
@override
|
||||
String get aliasedName => _alias ?? actualTableName;
|
||||
@override
|
||||
String get actualTableName => $name;
|
||||
static const String $name = 'ingredients';
|
||||
@override
|
||||
VerificationContext validateIntegrity(
|
||||
Insertable<IngredientTable> instance, {
|
||||
bool isInserting = false,
|
||||
}) {
|
||||
final context = VerificationContext();
|
||||
final data = instance.toColumns(true);
|
||||
if (data.containsKey('id')) {
|
||||
context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta));
|
||||
} else if (isInserting) {
|
||||
context.missing(_idMeta);
|
||||
}
|
||||
if (data.containsKey('data')) {
|
||||
context.handle(
|
||||
_dataMeta,
|
||||
this.data.isAcceptableOrUnknown(data['data']!, _dataMeta),
|
||||
);
|
||||
} else if (isInserting) {
|
||||
context.missing(_dataMeta);
|
||||
}
|
||||
if (data.containsKey('last_fetched')) {
|
||||
context.handle(
|
||||
_lastFetchedMeta,
|
||||
lastFetched.isAcceptableOrUnknown(
|
||||
data['last_fetched']!,
|
||||
_lastFetchedMeta,
|
||||
),
|
||||
);
|
||||
} else if (isInserting) {
|
||||
context.missing(_lastFetchedMeta);
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
@override
|
||||
Set<GeneratedColumn> get $primaryKey => const {};
|
||||
@override
|
||||
IngredientTable map(Map<String, dynamic> data, {String? tablePrefix}) {
|
||||
final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : '';
|
||||
return IngredientTable(
|
||||
id: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.int,
|
||||
data['${effectivePrefix}id'],
|
||||
)!,
|
||||
data: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.string,
|
||||
data['${effectivePrefix}data'],
|
||||
)!,
|
||||
lastFetched: attachedDatabase.typeMapping.read(
|
||||
DriftSqlType.dateTime,
|
||||
data['${effectivePrefix}last_fetched'],
|
||||
)!,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
$IngredientsTable createAlias(String alias) {
|
||||
return $IngredientsTable(attachedDatabase, alias);
|
||||
}
|
||||
}
|
||||
|
||||
class IngredientTable extends DataClass implements Insertable<IngredientTable> {
|
||||
final int id;
|
||||
final String data;
|
||||
|
||||
/// The date when the ingredient was last fetched from the server
|
||||
final DateTime lastFetched;
|
||||
const IngredientTable({
|
||||
required this.id,
|
||||
required this.data,
|
||||
required this.lastFetched,
|
||||
});
|
||||
@override
|
||||
Map<String, Expression> toColumns(bool nullToAbsent) {
|
||||
final map = <String, Expression>{};
|
||||
map['id'] = Variable<int>(id);
|
||||
map['data'] = Variable<String>(data);
|
||||
map['last_fetched'] = Variable<DateTime>(lastFetched);
|
||||
return map;
|
||||
}
|
||||
|
||||
IngredientsCompanion toCompanion(bool nullToAbsent) {
|
||||
return IngredientsCompanion(
|
||||
id: Value(id),
|
||||
data: Value(data),
|
||||
lastFetched: Value(lastFetched),
|
||||
);
|
||||
}
|
||||
|
||||
factory IngredientTable.fromJson(
|
||||
Map<String, dynamic> json, {
|
||||
ValueSerializer? serializer,
|
||||
}) {
|
||||
serializer ??= driftRuntimeOptions.defaultSerializer;
|
||||
return IngredientTable(
|
||||
id: serializer.fromJson<int>(json['id']),
|
||||
data: serializer.fromJson<String>(json['data']),
|
||||
lastFetched: serializer.fromJson<DateTime>(json['lastFetched']),
|
||||
);
|
||||
}
|
||||
@override
|
||||
Map<String, dynamic> toJson({ValueSerializer? serializer}) {
|
||||
serializer ??= driftRuntimeOptions.defaultSerializer;
|
||||
return <String, dynamic>{
|
||||
'id': serializer.toJson<int>(id),
|
||||
'data': serializer.toJson<String>(data),
|
||||
'lastFetched': serializer.toJson<DateTime>(lastFetched),
|
||||
};
|
||||
}
|
||||
|
||||
IngredientTable copyWith({int? id, String? data, DateTime? lastFetched}) => IngredientTable(
|
||||
id: id ?? this.id,
|
||||
data: data ?? this.data,
|
||||
lastFetched: lastFetched ?? this.lastFetched,
|
||||
);
|
||||
IngredientTable copyWithCompanion(IngredientsCompanion data) {
|
||||
return IngredientTable(
|
||||
id: data.id.present ? data.id.value : this.id,
|
||||
data: data.data.present ? data.data.value : this.data,
|
||||
lastFetched: data.lastFetched.present ? data.lastFetched.value : this.lastFetched,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return (StringBuffer('IngredientTable(')
|
||||
..write('id: $id, ')
|
||||
..write('data: $data, ')
|
||||
..write('lastFetched: $lastFetched')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(id, data, lastFetched);
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
(other is IngredientTable &&
|
||||
other.id == this.id &&
|
||||
other.data == this.data &&
|
||||
other.lastFetched == this.lastFetched);
|
||||
}
|
||||
|
||||
class IngredientsCompanion extends UpdateCompanion<IngredientTable> {
|
||||
final Value<int> id;
|
||||
final Value<String> data;
|
||||
final Value<DateTime> lastFetched;
|
||||
final Value<int> rowid;
|
||||
const IngredientsCompanion({
|
||||
this.id = const Value.absent(),
|
||||
this.data = const Value.absent(),
|
||||
this.lastFetched = const Value.absent(),
|
||||
this.rowid = const Value.absent(),
|
||||
});
|
||||
IngredientsCompanion.insert({
|
||||
required int id,
|
||||
required String data,
|
||||
required DateTime lastFetched,
|
||||
this.rowid = const Value.absent(),
|
||||
}) : id = Value(id),
|
||||
data = Value(data),
|
||||
lastFetched = Value(lastFetched);
|
||||
static Insertable<IngredientTable> custom({
|
||||
Expression<int>? id,
|
||||
Expression<String>? data,
|
||||
Expression<DateTime>? lastFetched,
|
||||
Expression<int>? rowid,
|
||||
}) {
|
||||
return RawValuesInsertable({
|
||||
if (id != null) 'id': id,
|
||||
if (data != null) 'data': data,
|
||||
if (lastFetched != null) 'last_fetched': lastFetched,
|
||||
if (rowid != null) 'rowid': rowid,
|
||||
});
|
||||
}
|
||||
|
||||
IngredientsCompanion copyWith({
|
||||
Value<int>? id,
|
||||
Value<String>? data,
|
||||
Value<DateTime>? lastFetched,
|
||||
Value<int>? rowid,
|
||||
}) {
|
||||
return IngredientsCompanion(
|
||||
id: id ?? this.id,
|
||||
data: data ?? this.data,
|
||||
lastFetched: lastFetched ?? this.lastFetched,
|
||||
rowid: rowid ?? this.rowid,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, Expression> toColumns(bool nullToAbsent) {
|
||||
final map = <String, Expression>{};
|
||||
if (id.present) {
|
||||
map['id'] = Variable<int>(id.value);
|
||||
}
|
||||
if (data.present) {
|
||||
map['data'] = Variable<String>(data.value);
|
||||
}
|
||||
if (lastFetched.present) {
|
||||
map['last_fetched'] = Variable<DateTime>(lastFetched.value);
|
||||
}
|
||||
if (rowid.present) {
|
||||
map['rowid'] = Variable<int>(rowid.value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return (StringBuffer('IngredientsCompanion(')
|
||||
..write('id: $id, ')
|
||||
..write('data: $data, ')
|
||||
..write('lastFetched: $lastFetched, ')
|
||||
..write('rowid: $rowid')
|
||||
..write(')'))
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
|
||||
abstract class _$IngredientDatabase extends GeneratedDatabase {
|
||||
_$IngredientDatabase(QueryExecutor e) : super(e);
|
||||
$IngredientDatabaseManager get managers => $IngredientDatabaseManager(this);
|
||||
late final $IngredientsTable ingredients = $IngredientsTable(this);
|
||||
@override
|
||||
Iterable<TableInfo<Table, Object?>> get allTables =>
|
||||
allSchemaEntities.whereType<TableInfo<Table, Object?>>();
|
||||
@override
|
||||
List<DatabaseSchemaEntity> get allSchemaEntities => [ingredients];
|
||||
}
|
||||
|
||||
typedef $$IngredientsTableCreateCompanionBuilder =
|
||||
IngredientsCompanion Function({
|
||||
required int id,
|
||||
required String data,
|
||||
required DateTime lastFetched,
|
||||
Value<int> rowid,
|
||||
});
|
||||
typedef $$IngredientsTableUpdateCompanionBuilder =
|
||||
IngredientsCompanion Function({
|
||||
Value<int> id,
|
||||
Value<String> data,
|
||||
Value<DateTime> lastFetched,
|
||||
Value<int> rowid,
|
||||
});
|
||||
|
||||
class $$IngredientsTableFilterComposer extends Composer<_$IngredientDatabase, $IngredientsTable> {
|
||||
$$IngredientsTableFilterComposer({
|
||||
required super.$db,
|
||||
required super.$table,
|
||||
super.joinBuilder,
|
||||
super.$addJoinBuilderToRootComposer,
|
||||
super.$removeJoinBuilderFromRootComposer,
|
||||
});
|
||||
ColumnFilters<int> get id => $composableBuilder(
|
||||
column: $table.id,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<String> get data => $composableBuilder(
|
||||
column: $table.data,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
|
||||
ColumnFilters<DateTime> get lastFetched => $composableBuilder(
|
||||
column: $table.lastFetched,
|
||||
builder: (column) => ColumnFilters(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$IngredientsTableOrderingComposer extends Composer<_$IngredientDatabase, $IngredientsTable> {
|
||||
$$IngredientsTableOrderingComposer({
|
||||
required super.$db,
|
||||
required super.$table,
|
||||
super.joinBuilder,
|
||||
super.$addJoinBuilderToRootComposer,
|
||||
super.$removeJoinBuilderFromRootComposer,
|
||||
});
|
||||
ColumnOrderings<int> get id => $composableBuilder(
|
||||
column: $table.id,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<String> get data => $composableBuilder(
|
||||
column: $table.data,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
|
||||
ColumnOrderings<DateTime> get lastFetched => $composableBuilder(
|
||||
column: $table.lastFetched,
|
||||
builder: (column) => ColumnOrderings(column),
|
||||
);
|
||||
}
|
||||
|
||||
class $$IngredientsTableAnnotationComposer
|
||||
extends Composer<_$IngredientDatabase, $IngredientsTable> {
|
||||
$$IngredientsTableAnnotationComposer({
|
||||
required super.$db,
|
||||
required super.$table,
|
||||
super.joinBuilder,
|
||||
super.$addJoinBuilderToRootComposer,
|
||||
super.$removeJoinBuilderFromRootComposer,
|
||||
});
|
||||
GeneratedColumn<int> get id => $composableBuilder(column: $table.id, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<String> get data =>
|
||||
$composableBuilder(column: $table.data, builder: (column) => column);
|
||||
|
||||
GeneratedColumn<DateTime> get lastFetched => $composableBuilder(
|
||||
column: $table.lastFetched,
|
||||
builder: (column) => column,
|
||||
);
|
||||
}
|
||||
|
||||
class $$IngredientsTableTableManager
|
||||
extends
|
||||
RootTableManager<
|
||||
_$IngredientDatabase,
|
||||
$IngredientsTable,
|
||||
IngredientTable,
|
||||
$$IngredientsTableFilterComposer,
|
||||
$$IngredientsTableOrderingComposer,
|
||||
$$IngredientsTableAnnotationComposer,
|
||||
$$IngredientsTableCreateCompanionBuilder,
|
||||
$$IngredientsTableUpdateCompanionBuilder,
|
||||
(
|
||||
IngredientTable,
|
||||
BaseReferences<_$IngredientDatabase, $IngredientsTable, IngredientTable>,
|
||||
),
|
||||
IngredientTable,
|
||||
PrefetchHooks Function()
|
||||
> {
|
||||
$$IngredientsTableTableManager(
|
||||
_$IngredientDatabase db,
|
||||
$IngredientsTable table,
|
||||
) : super(
|
||||
TableManagerState(
|
||||
db: db,
|
||||
table: table,
|
||||
createFilteringComposer: () => $$IngredientsTableFilterComposer($db: db, $table: table),
|
||||
createOrderingComposer: () => $$IngredientsTableOrderingComposer($db: db, $table: table),
|
||||
createComputedFieldComposer: () =>
|
||||
$$IngredientsTableAnnotationComposer($db: db, $table: table),
|
||||
updateCompanionCallback:
|
||||
({
|
||||
Value<int> id = const Value.absent(),
|
||||
Value<String> data = const Value.absent(),
|
||||
Value<DateTime> lastFetched = const Value.absent(),
|
||||
Value<int> rowid = const Value.absent(),
|
||||
}) => IngredientsCompanion(
|
||||
id: id,
|
||||
data: data,
|
||||
lastFetched: lastFetched,
|
||||
rowid: rowid,
|
||||
),
|
||||
createCompanionCallback:
|
||||
({
|
||||
required int id,
|
||||
required String data,
|
||||
required DateTime lastFetched,
|
||||
Value<int> rowid = const Value.absent(),
|
||||
}) => IngredientsCompanion.insert(
|
||||
id: id,
|
||||
data: data,
|
||||
lastFetched: lastFetched,
|
||||
rowid: rowid,
|
||||
),
|
||||
withReferenceMapper: (p0) =>
|
||||
p0.map((e) => (e.readTable(table), BaseReferences(db, table, e))).toList(),
|
||||
prefetchHooksCallback: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
typedef $$IngredientsTableProcessedTableManager =
|
||||
ProcessedTableManager<
|
||||
_$IngredientDatabase,
|
||||
$IngredientsTable,
|
||||
IngredientTable,
|
||||
$$IngredientsTableFilterComposer,
|
||||
$$IngredientsTableOrderingComposer,
|
||||
$$IngredientsTableAnnotationComposer,
|
||||
$$IngredientsTableCreateCompanionBuilder,
|
||||
$$IngredientsTableUpdateCompanionBuilder,
|
||||
(
|
||||
IngredientTable,
|
||||
BaseReferences<_$IngredientDatabase, $IngredientsTable, IngredientTable>,
|
||||
),
|
||||
IngredientTable,
|
||||
PrefetchHooks Function()
|
||||
>;
|
||||
|
||||
class $IngredientDatabaseManager {
|
||||
final _$IngredientDatabase _db;
|
||||
$IngredientDatabaseManager(this._db);
|
||||
$$IngredientsTableTableManager get ingredients =>
|
||||
$$IngredientsTableTableManager(_db, _db.ingredients);
|
||||
}
|
||||
154
lib/database/powersync/database.dart
Normal file
154
lib/database/powersync/database.dart
Normal file
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:drift_sqlite_async/drift_sqlite_async.dart';
|
||||
import 'package:flutter/material.dart' show TimeOfDay;
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/date_only_text_converter.dart';
|
||||
import 'package:wger/database/converters/exercise_image_style_converter.dart';
|
||||
import 'package:wger/database/converters/time_of_day_converter.dart';
|
||||
import 'package:wger/database/converters/utc_datetime_converter.dart';
|
||||
import 'package:wger/database/converters/workout_impression_converter.dart';
|
||||
import 'package:wger/models/body_weight/weight_entry.dart';
|
||||
import 'package:wger/models/core/language.dart';
|
||||
import 'package:wger/models/core/license.dart';
|
||||
import 'package:wger/models/exercises/alias.dart';
|
||||
import 'package:wger/models/exercises/category.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/gallery/image.dart';
|
||||
import 'package:wger/models/measurements/measurement_category.dart';
|
||||
import 'package:wger/models/measurements/measurement_entry.dart';
|
||||
import 'package:wger/models/nutrition/ingredient.dart';
|
||||
import 'package:wger/models/nutrition/ingredient_image.dart';
|
||||
import 'package:wger/models/nutrition/ingredient_weight_unit.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/models/user/user_profile.dart';
|
||||
import 'package:wger/models/workouts/log.dart';
|
||||
import 'package:wger/models/workouts/repetition_unit.dart';
|
||||
import 'package:wger/models/workouts/routine.dart';
|
||||
import 'package:wger/models/workouts/session.dart';
|
||||
import 'package:wger/models/workouts/weight_unit.dart';
|
||||
|
||||
import 'powersync.dart';
|
||||
import 'tables/exercise.dart';
|
||||
import 'tables/gallery.dart';
|
||||
import 'tables/ingredient.dart';
|
||||
import 'tables/language.dart';
|
||||
import 'tables/license.dart';
|
||||
import 'tables/measurements.dart';
|
||||
import 'tables/nutrition.dart';
|
||||
import 'tables/routines.dart';
|
||||
import 'tables/user_profile.dart';
|
||||
import 'tables/weight.dart';
|
||||
|
||||
part 'database.g.dart';
|
||||
|
||||
@DriftDatabase(
|
||||
tables: [
|
||||
// Core
|
||||
LanguageTable,
|
||||
LicenseTable,
|
||||
UserProfileTable,
|
||||
|
||||
// Exercises
|
||||
ExerciseTable,
|
||||
ExerciseTranslationTable,
|
||||
ExerciseAliasTable,
|
||||
ExerciseCommentTable,
|
||||
MuscleTable,
|
||||
ExerciseMuscleM2N,
|
||||
ExerciseSecondaryMuscleM2N,
|
||||
EquipmentTable,
|
||||
ExerciseEquipmentM2N,
|
||||
ExerciseCategoryTable,
|
||||
ExerciseImageTable,
|
||||
ExerciseVideoTable,
|
||||
|
||||
// Body weight
|
||||
WeightEntryTable,
|
||||
|
||||
// Measurements
|
||||
MeasurementCategoryTable,
|
||||
MeasurementEntryTable,
|
||||
|
||||
// Routines
|
||||
RoutineTable,
|
||||
WorkoutLogTable,
|
||||
WorkoutSessionTable,
|
||||
RoutineRepetitionUnitTable,
|
||||
RoutineWeightUnitTable,
|
||||
|
||||
// Nutrition
|
||||
NutritionalPlanTable,
|
||||
IngredientTable,
|
||||
IngredientImageTable,
|
||||
IngredientWeightUnitTable,
|
||||
MealTable,
|
||||
MealItemTable,
|
||||
LogItemTable,
|
||||
|
||||
// Gallery
|
||||
GalleryImageTable,
|
||||
],
|
||||
//include: {'queries.drift'},
|
||||
)
|
||||
class DriftPowersyncDatabase extends _$DriftPowersyncDatabase {
|
||||
DriftPowersyncDatabase(super.e);
|
||||
|
||||
@override
|
||||
int get schemaVersion => 1;
|
||||
|
||||
@override
|
||||
MigrationStrategy get migration {
|
||||
return MigrationStrategy(
|
||||
onCreate: (m) async {
|
||||
// We don't have to call createAll(), PowerSync instantiates the schema
|
||||
// for us. We can use the opportunity to create fts5 indexes though.
|
||||
},
|
||||
onUpgrade: (m, from, to) async {
|
||||
if (from == 1) {
|
||||
// await createFts5Tables(
|
||||
// db: this,
|
||||
// tableName: 'todos',
|
||||
// columns: ['description', 'list_id'],
|
||||
// );
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final driftPowerSyncDatabase = Provider((ref) {
|
||||
return DriftPowersyncDatabase(
|
||||
DatabaseConnection.delayed(
|
||||
Future(() async {
|
||||
final database = await ref.read(powerSyncInstanceProvider.future);
|
||||
return SqliteAsyncDriftConnection(database);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
22200
lib/database/powersync/database.g.dart
Normal file
22200
lib/database/powersync/database.g.dart
Normal file
File diff suppressed because it is too large
Load Diff
224
lib/database/powersync/powersync.dart
Normal file
224
lib/database/powersync/powersync.dart
Normal file
@@ -0,0 +1,224 @@
|
||||
/*
|
||||
* 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:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:powersync/powersync.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:stream_transform/stream_transform.dart';
|
||||
import 'package:wger/powersync/api_client.dart';
|
||||
import 'package:wger/powersync/connector.dart';
|
||||
import 'package:wger/powersync/schema.dart';
|
||||
import 'package:wger/providers/auth_http_client.dart';
|
||||
import 'package:wger/providers/network_provider.dart';
|
||||
import 'package:wger/providers/wger_base.dart';
|
||||
|
||||
part 'powersync.g.dart';
|
||||
|
||||
final _logger = Logger('powersync');
|
||||
|
||||
PowerSyncDatabase? _builtInstance;
|
||||
|
||||
/// The PowerSync database once [powerSyncInstanceProvider] has finished
|
||||
/// building, otherwise null.
|
||||
///
|
||||
/// Synchronous, build-free accessor for callers that should act on the DB only
|
||||
/// when it already exists (the auth notifier's session-reset paths). Awaiting
|
||||
/// [powerSyncInstanceProvider] through `ref` would instead be async and would
|
||||
/// build the DB on demand, the opposite of the no-op-when-absent behaviour
|
||||
/// those paths need.
|
||||
PowerSyncDatabase? get builtPowerSyncInstance => _builtInstance;
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<PowerSyncDatabase> powerSyncInstance(Ref ref) async {
|
||||
final db = PowerSyncDatabase(
|
||||
schema: schema,
|
||||
path: await _getDatabasePath(),
|
||||
logger: attachedLogger,
|
||||
);
|
||||
await db.initialize();
|
||||
await _createRawTables(db);
|
||||
_builtInstance = db;
|
||||
|
||||
final client = ref.read(authenticatedHttpClientProvider);
|
||||
|
||||
// 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
|
||||
// against an unreachable backend
|
||||
void syncConnection(bool isOnline) {
|
||||
if (isOnline) {
|
||||
final serverUrl = ref.read(wgerBaseProvider).serverUrl;
|
||||
if (serverUrl != null) {
|
||||
connectPowerSync(db, serverUrl, client);
|
||||
}
|
||||
} else {
|
||||
db.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
syncConnection(ref.read(networkStatusProvider));
|
||||
ref.listen(networkStatusProvider, (_, isOnline) => syncConnection(isOnline));
|
||||
|
||||
ref.onDispose(() {
|
||||
_builtInstance = null;
|
||||
db.close();
|
||||
});
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
/// Materialise the native SQLite tables for the raw entries declared in
|
||||
/// [schema]. PowerSync only manages the JSON view tables itself, so any
|
||||
/// `RawTable` entry must have its `CREATE TABLE`/`CREATE INDEX` statements
|
||||
/// applied by us.
|
||||
///
|
||||
/// Skips all work when the raw tables already exist, so warm restarts don't
|
||||
/// take a write lock on the DB.
|
||||
Future<void> _createRawTables(PowerSyncDatabase db) async {
|
||||
// Not STRICT: keep SQLite's type affinity behaviour so PowerSync's
|
||||
// inferred inserts can bind values as they arrive from the JSON wire
|
||||
// protocol without us having to coerce types up front.
|
||||
//
|
||||
// `id` is INTEGER, not the PowerSync-conventional TEXT, so it matches the
|
||||
// Drift `IntColumn id` and the integer `exercise_id` FK: the catalogue join
|
||||
// is then native INTEGER == INTEGER instead of relying on TEXT-vs-INTEGER
|
||||
// affinity coercion. PowerSync's string oplog id coerces to INTEGER on insert
|
||||
// (safe: Django exercise PKs are always numeric).
|
||||
const rawTables = ['exercises_exercise', 'exercises_translation'];
|
||||
final existing = await db.getAll(
|
||||
'SELECT name FROM sqlite_master '
|
||||
'WHERE type = ? AND name IN (${rawTables.map((_) => '?').join(', ')})',
|
||||
['table', ...rawTables],
|
||||
);
|
||||
|
||||
if (existing.length == rawTables.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
await db.writeTransaction((tx) async {
|
||||
await tx.execute('''
|
||||
CREATE TABLE IF NOT EXISTS exercises_exercise(
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
uuid TEXT,
|
||||
category_id INTEGER,
|
||||
variation_group TEXT,
|
||||
created TEXT,
|
||||
last_update TEXT
|
||||
)
|
||||
''');
|
||||
await tx.execute(
|
||||
'CREATE INDEX IF NOT EXISTS exercises_exercise__category '
|
||||
'ON exercises_exercise(category_id)',
|
||||
);
|
||||
await tx.execute(
|
||||
'CREATE INDEX IF NOT EXISTS exercises_exercise__variation '
|
||||
'ON exercises_exercise(variation_group)',
|
||||
);
|
||||
|
||||
await tx.execute('''
|
||||
CREATE TABLE IF NOT EXISTS exercises_translation(
|
||||
id INTEGER NOT NULL PRIMARY KEY,
|
||||
uuid TEXT,
|
||||
language_id INTEGER,
|
||||
exercise_id INTEGER,
|
||||
description TEXT,
|
||||
name TEXT,
|
||||
created TEXT,
|
||||
last_update TEXT
|
||||
)
|
||||
''');
|
||||
await tx.execute(
|
||||
'CREATE INDEX IF NOT EXISTS exercises_translation__language '
|
||||
'ON exercises_translation(language_id)',
|
||||
);
|
||||
await tx.execute(
|
||||
'CREATE INDEX IF NOT EXISTS exercises_translation__exercise '
|
||||
'ON exercises_translation(exercise_id)',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// Creates a fresh [DjangoConnector] for [baseUrl] and connects [db] to it.
|
||||
/// Used both at initial creation and after a logout/login cycle to pick up
|
||||
/// the new user's server URL / credentials. [client] is the authenticated
|
||||
/// HTTP client (see [authenticatedHttpClientProvider]); the connector reuses
|
||||
/// it for its REST calls so the same `Authorization` injection and
|
||||
/// pre-emptive refresh apply.
|
||||
void connectPowerSync(PowerSyncDatabase db, String baseUrl, http.Client client) {
|
||||
db.connect(
|
||||
connector: DjangoConnector(
|
||||
baseUrl: baseUrl,
|
||||
apiClient: ApiClient(baseUrl, client: client),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final _syncStatusInternal = StreamProvider<SyncStatus?>((ref) {
|
||||
return Stream.fromFuture(
|
||||
ref.watch(powerSyncInstanceProvider.future),
|
||||
).asyncExpand<SyncStatus?>((db) => db.statusStream).startWith(null);
|
||||
});
|
||||
|
||||
final syncStatus = Provider((ref) {
|
||||
// ignore: invalid_use_of_internal_member
|
||||
return ref.watch(_syncStatusInternal).value ?? const SyncStatus();
|
||||
});
|
||||
|
||||
Future<String> _getDatabasePath() async {
|
||||
const dbFilename = 'powersync-wger.db';
|
||||
|
||||
// getApplicationSupportDirectory is not supported on Web
|
||||
if (kIsWeb) {
|
||||
return dbFilename;
|
||||
}
|
||||
final dir = await getApplicationSupportDirectory();
|
||||
return join(dir.path, dbFilename);
|
||||
}
|
||||
|
||||
/// Deletes the on-disk PowerSync SQLite files (main DB plus WAL/SHM/journal
|
||||
/// sidecars). Used to purge a previous user's data on login as a different
|
||||
/// user when [powerSyncInstanceProvider] has not been built yet, so the
|
||||
/// usual `disconnectAndClear()` route is unavailable.
|
||||
///
|
||||
/// Best-effort: missing files are treated as success, individual delete
|
||||
/// failures are logged and swallowed so a single locked sidecar doesn't
|
||||
/// block the rest. On web the database is backed by IndexedDB rather than
|
||||
/// a real file, so this is a no-op there.
|
||||
Future<void> deletePowerSyncDatabaseFile() async {
|
||||
if (kIsWeb) {
|
||||
_logger.warning('deletePowerSyncDatabaseFile: not supported on web, skipping');
|
||||
return;
|
||||
}
|
||||
final path = await _getDatabasePath();
|
||||
for (final suffix in ['', '-wal', '-shm', '-journal']) {
|
||||
final file = File('$path$suffix');
|
||||
try {
|
||||
if (await file.exists()) {
|
||||
await file.delete();
|
||||
}
|
||||
} catch (e, s) {
|
||||
_logger.warning('deletePowerSyncDatabaseFile: failed to delete ${file.path}', e, s);
|
||||
}
|
||||
}
|
||||
}
|
||||
49
lib/database/powersync/powersync.g.dart
Normal file
49
lib/database/powersync/powersync.g.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'powersync.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(powerSyncInstance)
|
||||
final powerSyncInstanceProvider = PowerSyncInstanceProvider._();
|
||||
|
||||
final class PowerSyncInstanceProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<PowerSyncDatabase>,
|
||||
PowerSyncDatabase,
|
||||
FutureOr<PowerSyncDatabase>
|
||||
>
|
||||
with $FutureModifier<PowerSyncDatabase>, $FutureProvider<PowerSyncDatabase> {
|
||||
PowerSyncInstanceProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'powerSyncInstanceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$powerSyncInstanceHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<PowerSyncDatabase> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<PowerSyncDatabase> create(Ref ref) {
|
||||
return powerSyncInstance(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$powerSyncInstanceHash() => r'3cc3ce4ee4d65ab26f3709b7526822b0366f0eb6';
|
||||
353
lib/database/powersync/tables/exercise.dart
Normal file
353
lib/database/powersync/tables/exercise.dart
Normal file
@@ -0,0 +1,353 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/exercise_image_style_converter.dart';
|
||||
import 'package:wger/models/exercises/alias.dart';
|
||||
import 'package:wger/models/exercises/category.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 'language.dart';
|
||||
|
||||
@DataClassName('ExerciseRow')
|
||||
class ExerciseTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercise';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
TextColumn get variationGroup => text().nullable().named('variation_group')();
|
||||
IntColumn get categoryId =>
|
||||
integer().named('category_id').references(ExerciseCategoryTable, #id)();
|
||||
DateTimeColumn get created => dateTime()();
|
||||
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
|
||||
}
|
||||
|
||||
/// Raw table: native SQLite storage instead of the default JSON-view layer.
|
||||
/// Exercises are server-owned (read-only on the client) and dominate the
|
||||
/// per-row JSON decode cost, so bypassing the view layer is the lever with
|
||||
/// the biggest impact. The actual `CREATE TABLE` + `CREATE INDEX` statements
|
||||
/// live next to `PowerSyncDatabase.initialize()` in `database/powersync/powersync.dart`.
|
||||
const PowersyncExerciseTable = ps.RawTable.inferred(
|
||||
name: 'exercises_exercise',
|
||||
schema: ps.RawTableSchema(),
|
||||
);
|
||||
|
||||
@DataClassName('ExerciseTranslationRow')
|
||||
class ExerciseTranslationTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_translation';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
|
||||
IntColumn get languageId => integer().named('language_id').references(LanguageTable, #id)();
|
||||
TextColumn get name => text()();
|
||||
TextColumn get description => text()();
|
||||
DateTimeColumn get created => dateTime()();
|
||||
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
|
||||
}
|
||||
|
||||
/// See [PowersyncExerciseTable]: translations live in the same raw-table
|
||||
/// store for the same reason (2k+ rows, wide text columns).
|
||||
const PowersyncTranslationTable = ps.RawTable.inferred(
|
||||
name: 'exercises_translation',
|
||||
schema: ps.RawTableSchema(),
|
||||
);
|
||||
|
||||
@UseRowClass(Alias)
|
||||
class ExerciseAliasTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_alias';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get translationId =>
|
||||
integer().named('translation_id').references(ExerciseTranslationTable, #id)();
|
||||
TextColumn get alias => text()();
|
||||
}
|
||||
|
||||
const PowersyncExerciseAliasTable = ps.Table(
|
||||
'exercises_alias',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('translation_id'),
|
||||
ps.Column.text('alias'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('translation', [ps.IndexedColumn('translation_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(Comment)
|
||||
class ExerciseCommentTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercisecomment';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get translationId =>
|
||||
integer().named('translation_id').references(ExerciseTranslationTable, #id)();
|
||||
TextColumn get comment => text()();
|
||||
}
|
||||
|
||||
const PowersyncExerciseCommentTable = ps.Table(
|
||||
'exercises_exercisecomment',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('translation_id'),
|
||||
ps.Column.text('comment'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('translation', [ps.IndexedColumn('translation_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(ExerciseCategory)
|
||||
class ExerciseCategoryTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercisecategory';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get name => text()();
|
||||
}
|
||||
|
||||
const PowersyncExerciseCategoryTable = ps.Table(
|
||||
'exercises_exercisecategory',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(Equipment)
|
||||
class EquipmentTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_equipment';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get name => text()();
|
||||
}
|
||||
|
||||
const PowersyncEquipmentTable = ps.Table(
|
||||
'exercises_equipment',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
],
|
||||
);
|
||||
|
||||
class ExerciseEquipmentM2N extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercise_equipment';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
|
||||
IntColumn get equipmentId => integer().named('equipment_id').references(EquipmentTable, #id)();
|
||||
}
|
||||
|
||||
const PowersyncExerciseEquipmentM2N = ps.Table(
|
||||
'exercises_exercise_equipment',
|
||||
[
|
||||
ps.Column.integer('exercise_id'),
|
||||
ps.Column.integer('equipment_id'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('equipment', [ps.IndexedColumn('equipment_id')]),
|
||||
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(Muscle)
|
||||
class MuscleTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_muscle';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get name => text()();
|
||||
TextColumn get nameEn => text().named('name_en')();
|
||||
BoolColumn get isFront => boolean().named('is_front')();
|
||||
}
|
||||
|
||||
const PowersyncMuscleTable = ps.Table(
|
||||
'exercises_muscle',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
ps.Column.text('name_en'),
|
||||
ps.Column.integer('is_front'),
|
||||
],
|
||||
);
|
||||
|
||||
class ExerciseMuscleM2N extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercise_muscles';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
|
||||
IntColumn get muscleId => integer().named('muscle_id').references(MuscleTable, #id)();
|
||||
}
|
||||
|
||||
const PowersyncExerciseMuscleM2N = ps.Table(
|
||||
'exercises_exercise_muscles',
|
||||
[
|
||||
ps.Column.integer('exercise_id'),
|
||||
ps.Column.integer('muscle_id'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('muscle', [ps.IndexedColumn('muscle_id')]),
|
||||
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
class ExerciseSecondaryMuscleM2N extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercise_muscles_secondary';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
|
||||
IntColumn get muscleId => integer().named('muscle_id').references(MuscleTable, #id)();
|
||||
}
|
||||
|
||||
const PowersyncExerciseSecondaryMuscleM2N = ps.Table(
|
||||
'exercises_exercise_muscles_secondary',
|
||||
[
|
||||
ps.Column.integer('exercise_id'),
|
||||
ps.Column.integer('muscle_id'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('muscle', [ps.IndexedColumn('muscle_id')]),
|
||||
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(ExerciseImage)
|
||||
class ExerciseImageTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exerciseimage';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
|
||||
// Relative path under MEDIA_ROOT (Django's ImageField stores this)
|
||||
TextColumn get image => text()();
|
||||
BoolColumn get isMain => boolean().named('is_main')();
|
||||
BoolColumn get isAiGenerated => boolean().named('is_ai_generated')();
|
||||
TextColumn get style => text().map(const ExerciseImageStyleConverter())();
|
||||
IntColumn get width => integer().nullable()();
|
||||
IntColumn get height => integer().nullable()();
|
||||
DateTimeColumn get created => dateTime()();
|
||||
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
|
||||
|
||||
// License (TASL, Title / Author / Source / License). license_author may be
|
||||
// null on the server (TextField with null=True); the others are not-null
|
||||
// strings (possibly empty) on the server.
|
||||
IntColumn get licenseId => integer().named('license_id')();
|
||||
TextColumn get licenseTitle => text().named('license_title')();
|
||||
TextColumn get licenseObjectUrl => text().named('license_object_url')();
|
||||
TextColumn get licenseAuthor => text().named('license_author').nullable()();
|
||||
TextColumn get licenseAuthorUrl => text().named('license_author_url')();
|
||||
TextColumn get licenseDerivativeSourceUrl => text().named('license_derivative_source_url')();
|
||||
}
|
||||
|
||||
const PowersyncExerciseImageTable = ps.Table(
|
||||
'exercises_exerciseimage',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('exercise_id'),
|
||||
ps.Column.text('image'),
|
||||
ps.Column.integer('is_main'),
|
||||
ps.Column.integer('is_ai_generated'),
|
||||
ps.Column.text('style'),
|
||||
ps.Column.integer('width'),
|
||||
ps.Column.integer('height'),
|
||||
ps.Column.text('created'),
|
||||
ps.Column.text('last_update'),
|
||||
ps.Column.integer('license_id'),
|
||||
ps.Column.text('license_title'),
|
||||
ps.Column.text('license_object_url'),
|
||||
ps.Column.text('license_author'),
|
||||
ps.Column.text('license_author_url'),
|
||||
ps.Column.text('license_derivative_source_url'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
|
||||
ps.Index('license', [ps.IndexedColumn('license_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(Video)
|
||||
class ExerciseVideoTable extends Table {
|
||||
@override
|
||||
String get tableName => 'exercises_exercisevideo';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get exerciseId => integer().named('exercise_id').references(ExerciseTable, #id)();
|
||||
BoolColumn get isMain => boolean().named('is_main')();
|
||||
// Relative path under MEDIA_ROOT (Django's FileField stores this)
|
||||
TextColumn get video => text()();
|
||||
IntColumn get size => integer()();
|
||||
IntColumn get duration => integer()();
|
||||
IntColumn get width => integer()();
|
||||
IntColumn get height => integer()();
|
||||
TextColumn get codec => text()();
|
||||
TextColumn get codecLong => text().named('codec_long')();
|
||||
DateTimeColumn get created => dateTime()();
|
||||
DateTimeColumn get lastUpdate => dateTime().named('last_update')();
|
||||
|
||||
// License (TASL, Title / Author / Source / License). license_author may be
|
||||
// null on the server (TextField with null=True); the others are not-null
|
||||
// strings (possibly empty) on the server.
|
||||
IntColumn get licenseId => integer().named('license_id')();
|
||||
TextColumn get licenseTitle => text().named('license_title')();
|
||||
TextColumn get licenseObjectUrl => text().named('license_object_url')();
|
||||
TextColumn get licenseAuthor => text().named('license_author').nullable()();
|
||||
TextColumn get licenseAuthorUrl => text().named('license_author_url')();
|
||||
TextColumn get licenseDerivativeSourceUrl => text().named('license_derivative_source_url')();
|
||||
}
|
||||
|
||||
const PowersyncExerciseVideoTable = ps.Table(
|
||||
'exercises_exercisevideo',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('exercise_id'),
|
||||
ps.Column.integer('is_main'),
|
||||
ps.Column.text('video'),
|
||||
ps.Column.integer('size'),
|
||||
ps.Column.integer('duration'),
|
||||
ps.Column.integer('width'),
|
||||
ps.Column.integer('height'),
|
||||
ps.Column.text('codec'),
|
||||
ps.Column.text('codec_long'),
|
||||
ps.Column.text('created'),
|
||||
ps.Column.text('last_update'),
|
||||
ps.Column.integer('license_id'),
|
||||
ps.Column.text('license_title'),
|
||||
ps.Column.text('license_object_url'),
|
||||
ps.Column.text('license_author'),
|
||||
ps.Column.text('license_author_url'),
|
||||
ps.Column.text('license_derivative_source_url'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('exercise', [ps.IndexedColumn('exercise_id')]),
|
||||
ps.Index('license', [ps.IndexedColumn('license_id')]),
|
||||
],
|
||||
);
|
||||
42
lib/database/powersync/tables/gallery.dart
Normal file
42
lib/database/powersync/tables/gallery.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/date_only_text_converter.dart';
|
||||
import 'package:wger/models/gallery/image.dart';
|
||||
|
||||
@UseRowClass(GalleryImage)
|
||||
class GalleryImageTable extends Table {
|
||||
@override
|
||||
String get tableName => 'gallery_image';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get date => text().map(const DateOnlyTextConverter())();
|
||||
TextColumn get imagePath => text().named('image')();
|
||||
TextColumn get description => text()();
|
||||
}
|
||||
|
||||
const PowersyncGalleryImageTable = ps.Table(
|
||||
'gallery_image',
|
||||
[
|
||||
ps.Column.text('date'),
|
||||
ps.Column.text('image'),
|
||||
ps.Column.text('description'),
|
||||
],
|
||||
);
|
||||
177
lib/database/powersync/tables/ingredient.dart
Normal file
177
lib/database/powersync/tables/ingredient.dart
Normal file
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/utc_datetime_converter.dart';
|
||||
import 'package:wger/models/nutrition/ingredient.dart';
|
||||
import 'package:wger/models/nutrition/ingredient_image.dart' show IngredientImage;
|
||||
import 'package:wger/models/nutrition/ingredient_weight_unit.dart' show IngredientWeightUnit;
|
||||
|
||||
@UseRowClass(Ingredient)
|
||||
class IngredientTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_ingredient';
|
||||
|
||||
// Numerical id from the remote API
|
||||
IntColumn get id => integer()();
|
||||
|
||||
// Local client UUID for sync purposes
|
||||
TextColumn get uuid => text().clientDefault(() => ps.uuid.v4())();
|
||||
|
||||
// Other metadata
|
||||
IntColumn get languageId => integer().named('language_id')();
|
||||
TextColumn get remoteId => text().nullable().named('remote_id')();
|
||||
TextColumn get sourceName => text().nullable().named('source_name')();
|
||||
TextColumn get sourceUrl => text().nullable().named('source_url')();
|
||||
TextColumn get licenseObjectURl => text().named('license_object_url').nullable()();
|
||||
|
||||
// Product code / barcode
|
||||
TextColumn get code => text().nullable()();
|
||||
|
||||
// Display name (required)
|
||||
TextColumn get name => text()();
|
||||
|
||||
// Brand of the product
|
||||
TextColumn get brand => text().nullable()();
|
||||
|
||||
// Creation timestamp from server
|
||||
DateTimeColumn get created => dateTime().map(const UtcDateTimeConverter())();
|
||||
|
||||
// Energy and macronutrients
|
||||
IntColumn get energy => integer()();
|
||||
RealColumn get carbohydrates => real()();
|
||||
RealColumn get carbohydratesSugar => real().nullable().named('carbohydrates_sugar')();
|
||||
RealColumn get protein => real()();
|
||||
RealColumn get fat => real()();
|
||||
RealColumn get fatSaturated => real().nullable().named('fat_saturated')();
|
||||
RealColumn get fiber => real().nullable()();
|
||||
RealColumn get sodium => real().nullable()();
|
||||
|
||||
BoolColumn get isVegan => boolean().nullable().named('is_vegan')();
|
||||
BoolColumn get isVegetarian => boolean().nullable().named('is_vegetarian')();
|
||||
|
||||
// Stored as a single character ('a'–'e') matching `NutriScore.<x>.name`.
|
||||
Column<String> get nutriscore => textEnum<NutriScore>().nullable()();
|
||||
}
|
||||
|
||||
const PowersyncIngredientTable = ps.Table(
|
||||
'nutrition_ingredient',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('language_id'),
|
||||
ps.Column.text('remote_id'),
|
||||
ps.Column.text('source_name'),
|
||||
ps.Column.text('source_url'),
|
||||
ps.Column.text('license_object_url'),
|
||||
ps.Column.text('code'),
|
||||
ps.Column.text('name'),
|
||||
ps.Column.text('brand'),
|
||||
ps.Column.text('created'),
|
||||
ps.Column.integer('energy'),
|
||||
ps.Column.real('carbohydrates'),
|
||||
ps.Column.real('carbohydrates_sugar'),
|
||||
ps.Column.real('protein'),
|
||||
ps.Column.real('fat'),
|
||||
ps.Column.real('fat_saturated'),
|
||||
ps.Column.real('fiber'),
|
||||
ps.Column.real('sodium'),
|
||||
ps.Column.integer('is_vegan'),
|
||||
ps.Column.integer('is_vegetarian'),
|
||||
ps.Column.text('nutriscore'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('language_idx', [ps.IndexedColumn('language_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(IngredientImage)
|
||||
class IngredientImageTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_image';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get ingredientId => integer().named('ingredient_id').references(IngredientTable, #id)();
|
||||
// Relative path under MEDIA_ROOT (Django's ImageField stores this)
|
||||
TextColumn get image => text()();
|
||||
IntColumn get size => integer()();
|
||||
IntColumn get width => integer()();
|
||||
IntColumn get height => integer()();
|
||||
DateTimeColumn get created => dateTime().map(const UtcDateTimeConverter())();
|
||||
DateTimeColumn get lastUpdate =>
|
||||
dateTime().named('last_update').map(const UtcDateTimeConverter())();
|
||||
|
||||
// License (TASL). license_author may be null on the server (TextField with
|
||||
// null=True); the others are not-null strings (possibly empty).
|
||||
IntColumn get licenseId => integer().named('license_id')();
|
||||
TextColumn get author => text().named('license_author').nullable()();
|
||||
TextColumn get authorUrl => text().named('license_author_url')();
|
||||
TextColumn get title => text().named('license_title')();
|
||||
TextColumn get objectUrl => text().named('license_object_url')();
|
||||
TextColumn get derivativeSourceUrl => text().named('license_derivative_source_url')();
|
||||
}
|
||||
|
||||
const PowersyncIngredientImageTable = ps.Table(
|
||||
'nutrition_image',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('ingredient_id'),
|
||||
ps.Column.text('image'),
|
||||
ps.Column.integer('size'),
|
||||
ps.Column.integer('width'),
|
||||
ps.Column.integer('height'),
|
||||
ps.Column.text('created'),
|
||||
ps.Column.text('last_update'),
|
||||
ps.Column.integer('license_id'),
|
||||
ps.Column.text('license_author'),
|
||||
ps.Column.text('license_author_url'),
|
||||
ps.Column.text('license_title'),
|
||||
ps.Column.text('license_object_url'),
|
||||
ps.Column.text('license_derivative_source_url'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('ingredient_idx', [ps.IndexedColumn('ingredient_id')]),
|
||||
ps.Index('license_idx', [ps.IndexedColumn('license_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(IngredientWeightUnit)
|
||||
class IngredientWeightUnitTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_ingredientweightunit';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get uuid => text()();
|
||||
IntColumn get ingredientId => integer().named('ingredient_id').references(IngredientTable, #id)();
|
||||
TextColumn get name => text()();
|
||||
IntColumn get grams => integer().named('gram')();
|
||||
}
|
||||
|
||||
const PowersyncIngredientWeightUnitTable = ps.Table(
|
||||
'nutrition_ingredientweightunit',
|
||||
[
|
||||
ps.Column.text('uuid'),
|
||||
ps.Column.integer('ingredient_id'),
|
||||
ps.Column.text('name'),
|
||||
ps.Column.integer('gram'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('ingredient_idx', [ps.IndexedColumn('ingredient_id')]),
|
||||
],
|
||||
);
|
||||
39
lib/database/powersync/tables/language.dart
Normal file
39
lib/database/powersync/tables/language.dart
Normal file
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/models/core/language.dart';
|
||||
|
||||
@UseRowClass(Language)
|
||||
class LanguageTable extends Table {
|
||||
@override
|
||||
String get tableName => 'core_language';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get shortName => text().named('short_name')();
|
||||
TextColumn get fullName => text().named('full_name')();
|
||||
}
|
||||
|
||||
const PowersyncLanguageTable = ps.Table(
|
||||
'core_language',
|
||||
[
|
||||
ps.Column.text('short_name'),
|
||||
ps.Column.text('full_name'),
|
||||
],
|
||||
);
|
||||
41
lib/database/powersync/tables/license.dart
Normal file
41
lib/database/powersync/tables/license.dart
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/models/core/license.dart';
|
||||
|
||||
@UseRowClass(License)
|
||||
class LicenseTable extends Table {
|
||||
@override
|
||||
String get tableName => 'core_license';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get shortName => text().named('short_name')();
|
||||
TextColumn get fullName => text().named('full_name')();
|
||||
TextColumn get url => text()();
|
||||
}
|
||||
|
||||
const PowersyncLicenseTable = ps.Table(
|
||||
'core_license',
|
||||
[
|
||||
ps.Column.text('short_name'),
|
||||
ps.Column.text('full_name'),
|
||||
ps.Column.text('url'),
|
||||
],
|
||||
);
|
||||
69
lib/database/powersync/tables/measurements.dart
Normal file
69
lib/database/powersync/tables/measurements.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/utc_datetime_converter.dart';
|
||||
import 'package:wger/models/measurements/measurement_category.dart';
|
||||
import 'package:wger/models/measurements/measurement_entry.dart';
|
||||
|
||||
@UseRowClass(MeasurementCategory)
|
||||
class MeasurementCategoryTable extends Table {
|
||||
@override
|
||||
String get tableName => 'measurements_category';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
|
||||
TextColumn get name => text()();
|
||||
TextColumn get unit => text()();
|
||||
}
|
||||
|
||||
const PowersyncMeasurementCategoryTable = ps.Table(
|
||||
'measurements_category',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
ps.Column.text('unit'),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(MeasurementEntry)
|
||||
class MeasurementEntryTable extends Table {
|
||||
@override
|
||||
String get tableName => 'measurements_measurement';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
TextColumn get categoryId =>
|
||||
text().named('category_id').references(MeasurementCategoryTable, #id)();
|
||||
|
||||
DateTimeColumn get date => dateTime().map(const UtcDateTimeConverter())();
|
||||
RealColumn get value => real()();
|
||||
TextColumn get notes => text()();
|
||||
}
|
||||
|
||||
const PowersyncMeasurementEntryTable = ps.Table(
|
||||
'measurements_measurement',
|
||||
[
|
||||
ps.Column.text('category_id'),
|
||||
ps.Column.text('date'),
|
||||
ps.Column.real('value'),
|
||||
ps.Column.text('notes'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('category_idx', [ps.IndexedColumn('category_id')]),
|
||||
],
|
||||
);
|
||||
166
lib/database/powersync/tables/nutrition.dart
Normal file
166
lib/database/powersync/tables/nutrition.dart
Normal file
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:flutter/material.dart' show TimeOfDay;
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/date_only_text_converter.dart';
|
||||
import 'package:wger/database/converters/time_of_day_converter.dart';
|
||||
import 'package:wger/database/converters/utc_datetime_converter.dart';
|
||||
import 'package:wger/database/powersync/tables/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';
|
||||
|
||||
@UseRowClass(NutritionalPlan)
|
||||
class NutritionalPlanTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_nutritionplan';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
TextColumn get description => text()();
|
||||
DateTimeColumn get creationDate => dateTime().named('creation_date')();
|
||||
TextColumn get startDate => text().named('start').map(const DateOnlyTextConverter())();
|
||||
TextColumn get endDate => text().named('end').nullable().map(const DateOnlyTextConverter())();
|
||||
BoolColumn get onlyLogging => boolean().named('only_logging')();
|
||||
IntColumn get goalEnergy => integer().named('goal_energy').nullable()();
|
||||
IntColumn get goalProtein => integer().named('goal_protein').nullable()();
|
||||
IntColumn get goalCarbohydrates => integer().named('goal_carbohydrates').nullable()();
|
||||
IntColumn get goalFiber => integer().named('goal_fiber').nullable()();
|
||||
IntColumn get goalFat => integer().named('goal_fat').nullable()();
|
||||
BoolColumn get hasGoalCalories => boolean().named('has_goal_calories')();
|
||||
}
|
||||
|
||||
const PowersyncNutritionalPlanTable = ps.Table(
|
||||
'nutrition_nutritionplan',
|
||||
[
|
||||
ps.Column.text('description'),
|
||||
ps.Column.text('creation_date'),
|
||||
ps.Column.text('start'),
|
||||
ps.Column.text('end'),
|
||||
ps.Column.integer('only_logging'),
|
||||
ps.Column.integer('goal_energy'),
|
||||
ps.Column.integer('goal_protein'),
|
||||
ps.Column.integer('goal_carbohydrates'),
|
||||
ps.Column.integer('goal_fiber'),
|
||||
ps.Column.integer('goal_fat'),
|
||||
ps.Column.integer('has_goal_calories'),
|
||||
],
|
||||
);
|
||||
|
||||
/// Diary log entries (`nutrition_logitem`).
|
||||
///
|
||||
/// The client identifies rows by uuid; the sync rules emit
|
||||
/// `SELECT uuid AS id` so locally we just see a TEXT primary key. The
|
||||
/// integer `LogItem.id` from the backend stays server-side.
|
||||
@UseRowClass(LogItem)
|
||||
class LogItemTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_logitem';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
TextColumn get planId => text().named('plan_id').references(NutritionalPlanTable, #id)();
|
||||
TextColumn get mealId => text().nullable().named('meal_id')();
|
||||
IntColumn get ingredientId => integer().named('ingredient_id').references(IngredientTable, #id)();
|
||||
IntColumn get weightUnitId => integer().nullable().named('weight_unit_id')();
|
||||
DateTimeColumn get datetime => dateTime().map(const UtcDateTimeConverter())();
|
||||
RealColumn get amount => real()();
|
||||
TextColumn get comment => text().nullable()();
|
||||
}
|
||||
|
||||
const PowersyncLogItemTable = ps.Table(
|
||||
'nutrition_logitem',
|
||||
[
|
||||
ps.Column.text('plan_id'),
|
||||
ps.Column.text('meal_id'),
|
||||
ps.Column.integer('ingredient_id'),
|
||||
ps.Column.integer('weight_unit_id'),
|
||||
ps.Column.text('datetime'),
|
||||
ps.Column.real('amount'),
|
||||
ps.Column.text('comment'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('plan_idx', [ps.IndexedColumn('plan_id')]),
|
||||
ps.Index('ingredient_idx', [ps.IndexedColumn('ingredient_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
/// A meal inside a nutritional plan (`nutrition_meal`).
|
||||
///
|
||||
/// Identified by uuid client-side; creation, edits and deletes all flow
|
||||
/// through PowerSync. The `time` is stored as a `HH:MM:SS` string and
|
||||
/// translated to/from [TimeOfDay] via [TimeOfDayConverter].
|
||||
@UseRowClass(Meal, constructor: 'fromDrift')
|
||||
class MealTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_meal';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
TextColumn get planId => text().named('plan_id').references(NutritionalPlanTable, #id)();
|
||||
IntColumn get order => integer().withDefault(const Constant(1))();
|
||||
TextColumn get time => text().map(const TimeOfDayConverter()).nullable()();
|
||||
TextColumn get name => text().withDefault(const Constant(''))();
|
||||
}
|
||||
|
||||
const PowersyncMealTable = ps.Table(
|
||||
'nutrition_meal',
|
||||
[
|
||||
ps.Column.text('plan_id'),
|
||||
ps.Column.integer('order'),
|
||||
ps.Column.text('time'),
|
||||
ps.Column.text('name'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('plan_idx', [ps.IndexedColumn('plan_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
/// A single ingredient + amount inside a meal (`nutrition_mealitem`).
|
||||
///
|
||||
/// Identified by uuid client-side; the `meal_id` FK is the parent meal's
|
||||
/// uuid (not the server-side integer PK). `amount` is a
|
||||
/// `DecimalField(decimal_places=2, max_digits=6)` server-side, stored here
|
||||
/// as REAL, the rounding happens implicitly when DRF coerces back.
|
||||
@UseRowClass(MealItem, constructor: 'fromDrift')
|
||||
class MealItemTable extends Table {
|
||||
@override
|
||||
String get tableName => 'nutrition_mealitem';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
TextColumn get mealId => text().named('meal_id').references(MealTable, #id)();
|
||||
IntColumn get ingredientId => integer().named('ingredient_id').references(IngredientTable, #id)();
|
||||
IntColumn get weightUnitId => integer().named('weight_unit_id').nullable()();
|
||||
IntColumn get order => integer().withDefault(const Constant(1))();
|
||||
RealColumn get amount => real()();
|
||||
}
|
||||
|
||||
const PowersyncMealItemTable = ps.Table(
|
||||
'nutrition_mealitem',
|
||||
[
|
||||
ps.Column.text('meal_id'),
|
||||
ps.Column.integer('ingredient_id'),
|
||||
ps.Column.integer('weight_unit_id'),
|
||||
ps.Column.integer('order'),
|
||||
ps.Column.real('amount'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('meal_idx', [ps.IndexedColumn('meal_id')]),
|
||||
ps.Index('ingredient_idx', [ps.IndexedColumn('ingredient_id')]),
|
||||
],
|
||||
);
|
||||
178
lib/database/powersync/tables/routines.dart
Normal file
178
lib/database/powersync/tables/routines.dart
Normal file
@@ -0,0 +1,178 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/date_only_text_converter.dart';
|
||||
import 'package:wger/database/converters/time_of_day_converter.dart';
|
||||
import 'package:wger/database/converters/utc_datetime_converter.dart';
|
||||
import 'package:wger/database/converters/workout_impression_converter.dart';
|
||||
import 'package:wger/models/workouts/log.dart';
|
||||
import 'package:wger/models/workouts/repetition_unit.dart';
|
||||
import 'package:wger/models/workouts/routine.dart';
|
||||
import 'package:wger/models/workouts/session.dart';
|
||||
import 'package:wger/models/workouts/weight_unit.dart';
|
||||
|
||||
@UseRowClass(Routine)
|
||||
class RoutineTable extends Table {
|
||||
@override
|
||||
String get tableName => 'manager_routine';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get name => text()();
|
||||
TextColumn get description => text()();
|
||||
DateTimeColumn get created => dateTime().map(const UtcDateTimeConverter())();
|
||||
TextColumn get start => text().map(const DateOnlyTextConverter())();
|
||||
TextColumn get end => text().map(const DateOnlyTextConverter())();
|
||||
BoolColumn get isTemplate => boolean().named('is_template')();
|
||||
BoolColumn get isPublic => boolean().named('is_public')();
|
||||
BoolColumn get fitInWeek => boolean().named('fit_in_week')();
|
||||
}
|
||||
|
||||
const PowersyncRoutineTable = ps.Table(
|
||||
'manager_routine',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
ps.Column.text('description'),
|
||||
ps.Column.text('created'),
|
||||
ps.Column.text('start'),
|
||||
ps.Column.text('end'),
|
||||
ps.Column.integer('is_template'),
|
||||
ps.Column.integer('is_public'),
|
||||
ps.Column.integer('fit_in_week'),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(Log)
|
||||
class WorkoutLogTable extends Table {
|
||||
@override
|
||||
String get tableName => 'manager_workoutlog';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
IntColumn get exerciseId => integer().named('exercise_id')();
|
||||
IntColumn get routineId => integer().named('routine_id')();
|
||||
TextColumn get sessionId => text().named('session_id').nullable()();
|
||||
IntColumn get iteration => integer().nullable()();
|
||||
IntColumn get slotEntryId => integer().named('slot_entry_id').nullable()();
|
||||
|
||||
RealColumn get rir => real().nullable()();
|
||||
RealColumn get rirTarget => real().named('rir_target').nullable()();
|
||||
|
||||
RealColumn get repetitions => real().nullable()();
|
||||
RealColumn get repetitionsTarget => real().nullable().named('repetitions_target')();
|
||||
IntColumn get repetitionsUnitId => integer().named('repetitions_unit_id').nullable()();
|
||||
|
||||
RealColumn get weight => real().nullable()();
|
||||
RealColumn get weightTarget => real().nullable().named('weight_target')();
|
||||
IntColumn get weightUnitId => integer().nullable().named('weight_unit_id')();
|
||||
|
||||
DateTimeColumn get date => dateTime().map(const UtcDateTimeConverter())();
|
||||
}
|
||||
|
||||
const PowersyncWorkoutLogTable = ps.Table(
|
||||
'manager_workoutlog',
|
||||
[
|
||||
ps.Column.integer('exercise_id'),
|
||||
ps.Column.integer('routine_id'),
|
||||
ps.Column.text('session_id'),
|
||||
ps.Column.integer('iteration'),
|
||||
ps.Column.integer('slot_entry_id'),
|
||||
ps.Column.real('rir'),
|
||||
ps.Column.real('rir_target'),
|
||||
ps.Column.real('repetitions'),
|
||||
ps.Column.real('repetitions_target'),
|
||||
ps.Column.integer('repetitions_unit_id'),
|
||||
ps.Column.real('weight'),
|
||||
ps.Column.real('weight_target'),
|
||||
ps.Column.integer('weight_unit_id'),
|
||||
ps.Column.text('date'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('exercise_idx', [ps.IndexedColumn('exercise_id')]),
|
||||
ps.Index('slot_entry_idx', [ps.IndexedColumn('slot_entry_id')]),
|
||||
ps.Index('routine_idx', [ps.IndexedColumn('routine_id')]),
|
||||
ps.Index('session_idx', [ps.IndexedColumn('session_id')]),
|
||||
ps.Index('repetitions_unit_idx', [ps.IndexedColumn('repetitions_unit_id')]),
|
||||
ps.Index('weight_unit_idx', [ps.IndexedColumn('weight_unit_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(WorkoutSession)
|
||||
class WorkoutSessionTable extends Table {
|
||||
@override
|
||||
String get tableName => 'manager_workoutsession';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
IntColumn get routineId => integer().named('routine_id').nullable()();
|
||||
IntColumn get dayId => integer().named('day_id').nullable()();
|
||||
TextColumn get date => text().map(const DateOnlyTextConverter())();
|
||||
TextColumn get notes => text().nullable()();
|
||||
TextColumn get impression => text().map(const WorkoutImpressionConverter())();
|
||||
TextColumn get timeStart =>
|
||||
text().named('time_start').nullable().map(const TimeOfDayConverter())();
|
||||
TextColumn get timeEnd => text().named('time_end').nullable().map(const TimeOfDayConverter())();
|
||||
}
|
||||
|
||||
const PowersyncWorkoutSessionTable = ps.Table(
|
||||
'manager_workoutsession',
|
||||
[
|
||||
ps.Column.integer('routine_id'),
|
||||
ps.Column.integer('day_id'),
|
||||
ps.Column.text('date'),
|
||||
ps.Column.text('notes'),
|
||||
ps.Column.text('impression'),
|
||||
ps.Column.text('time_start'),
|
||||
ps.Column.text('time_end'),
|
||||
],
|
||||
indexes: [
|
||||
ps.Index('routine_idx', [ps.IndexedColumn('routine_id')]),
|
||||
ps.Index('day_idx', [ps.IndexedColumn('day_id')]),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(RepetitionUnit)
|
||||
class RoutineRepetitionUnitTable extends Table {
|
||||
@override
|
||||
String get tableName => 'core_repetitionunit';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get name => text()();
|
||||
}
|
||||
|
||||
const PowersyncRoutineRepetitionUnitTable = ps.Table(
|
||||
'core_repetitionunit',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
],
|
||||
);
|
||||
|
||||
@UseRowClass(WeightUnit)
|
||||
class RoutineWeightUnitTable extends Table {
|
||||
@override
|
||||
String get tableName => 'core_weightunit';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get name => text()();
|
||||
}
|
||||
|
||||
const PowersyncRoutineWeightUnitTable = ps.Table(
|
||||
'core_weightunit',
|
||||
[
|
||||
ps.Column.text('name'),
|
||||
],
|
||||
);
|
||||
37
lib/database/powersync/tables/user_profile.dart
Normal file
37
lib/database/powersync/tables/user_profile.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/models/user/user_profile.dart';
|
||||
|
||||
@UseRowClass(UserProfile)
|
||||
class UserProfileTable extends Table {
|
||||
@override
|
||||
String get tableName => 'core_userprofile';
|
||||
|
||||
IntColumn get id => integer()();
|
||||
TextColumn get weightUnitStr => text().named('weight_unit')();
|
||||
}
|
||||
|
||||
const PowersyncUserProfileTable = ps.Table(
|
||||
'core_userprofile',
|
||||
[
|
||||
ps.Column.text('weight_unit'),
|
||||
],
|
||||
);
|
||||
40
lib/database/powersync/tables/weight.dart
Normal file
40
lib/database/powersync/tables/weight.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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:drift/drift.dart';
|
||||
import 'package:powersync/powersync.dart' as ps;
|
||||
import 'package:wger/database/converters/utc_datetime_converter.dart';
|
||||
import 'package:wger/models/body_weight/weight_entry.dart';
|
||||
|
||||
@UseRowClass(WeightEntry)
|
||||
class WeightEntryTable extends Table {
|
||||
@override
|
||||
String get tableName => 'weight_weightentry';
|
||||
|
||||
TextColumn get id => text().clientDefault(() => ps.uuid.v7())();
|
||||
RealColumn get weight => real()();
|
||||
DateTimeColumn get date => dateTime().nullable().map(const UtcDateTimeConverter())();
|
||||
}
|
||||
|
||||
const PowersyncWeightEntryTable = ps.Table(
|
||||
'weight_weightentry',
|
||||
[
|
||||
ps.Column.real('weight'),
|
||||
ps.Column.text('date'),
|
||||
],
|
||||
);
|
||||
@@ -19,6 +19,13 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
/// Minimum server version required by this version of the app.
|
||||
///
|
||||
/// Bump this value whenever you depend on API changes that are only available
|
||||
/// in a newer server release. The check is performed during login and
|
||||
/// auto-login and mirrors what the server does with MIN_APP_VERSION.
|
||||
const MIN_SERVER_VERSION = '2.5';
|
||||
|
||||
/// Size for the "smaller" icons, e.g. when they belong to less important items
|
||||
/// and we don't want to fill the whole screen
|
||||
const double ICON_SIZE_SMALL = 20;
|
||||
@@ -31,16 +38,6 @@ const DEFAULT_SERVER_TEST = 'https://dev.wger.de';
|
||||
const TESTSERVER_USER_NAME = 'user';
|
||||
const TESTSERVER_PASSWORD = 'flutteruser';
|
||||
|
||||
/// Minimum server version required by this version of the app.
|
||||
///
|
||||
/// Bump this value whenever you depend on API changes that are only available
|
||||
/// in a newer server release. The check is performed during login and
|
||||
/// auto-login and mirrors what the server does with MIN_APP_VERSION.
|
||||
const MIN_SERVER_VERSION = '2.5';
|
||||
|
||||
/// Default impression for a workout session (neutral)
|
||||
const DEFAULT_IMPRESSION = 2;
|
||||
|
||||
// Weight and repetition units for the workout logs
|
||||
const REP_UNIT_REPETITIONS_ID = 1;
|
||||
const REP_UNIT_TILL_FAILURE_ID = 2;
|
||||
@@ -55,11 +52,6 @@ const DAYS_TO_CACHE = 20;
|
||||
const SUBMIT_BUTTON_KEY_NAME = 'submit-button';
|
||||
|
||||
/// Local Preferences keys
|
||||
const PREFS_EXERCISES = 'exerciseData';
|
||||
const PREFS_LAST_UPDATED_MUSCLES = 'lastUpdatedMuscles';
|
||||
const PREFS_LAST_UPDATED_EQUIPMENT = 'lastUpdatedEquipment';
|
||||
const PREFS_LAST_UPDATED_CATEGORIES = 'lastUpdatedCategories';
|
||||
const PREFS_LAST_UPDATED_LANGUAGES = 'lastUpdatedLanguages';
|
||||
const PREFS_INGREDIENTS = 'ingredientData';
|
||||
const PREFS_WORKOUT_UNITS = 'workoutUnits';
|
||||
const PREFS_USER = 'userData';
|
||||
@@ -67,6 +59,44 @@ const PREFS_USER_DARK_THEME = 'userDarkMode';
|
||||
const PREFS_USER_LOCALE = 'userLocale';
|
||||
const PREFS_LAST_SERVER = 'lastServer';
|
||||
|
||||
/// Headless JWT auth: SharedPreferences keys.
|
||||
///
|
||||
/// Read in parallel with the legacy `PREFS_USER` blob during the migration
|
||||
/// window; once a user logs in via the headless flow these supersede it.
|
||||
/// The refresh token is **not** stored here, it lives in secure storage
|
||||
/// (`SECURE_STORAGE_REFRESH_TOKEN`).
|
||||
const PREFS_ACCESS_TOKEN = 'accessToken';
|
||||
const PREFS_ACCESS_EXPIRES_AT = 'accessExpiresAt';
|
||||
const PREFS_TOKEN_TYPE = 'tokenType';
|
||||
const PREFS_SERVER_URL = 'serverUrl';
|
||||
|
||||
/// JWT `sub` of the user whose data is materialised in the local PowerSync
|
||||
/// DB. Compared on login to wipe the DB only on a genuine user switch.
|
||||
const PREFS_DB_OWNER_USER_ID = 'dbOwnerUserId';
|
||||
|
||||
/// User preference: keep the local PowerSync DB on logout instead of wiping
|
||||
/// it. Defaults to [KEEP_DATA_ON_LOGOUT_DEFAULT].
|
||||
const PREFS_KEEP_DATA_ON_LOGOUT = 'keepDataOnLogout';
|
||||
const KEEP_DATA_ON_LOGOUT_DEFAULT = true;
|
||||
|
||||
/// Secure-storage key for the headless refresh token.
|
||||
const SECURE_STORAGE_REFRESH_TOKEN = 'wger_refresh_token';
|
||||
|
||||
/// Login-CSRF defence for the web-handoff flow. Stored in SharedPreferences
|
||||
/// (not a secret, just a one-shot nonce echoed back by the server).
|
||||
const PREFS_APP_AUTH_STATE = 'appAuthState';
|
||||
const PREFS_APP_AUTH_STATE_AT = 'appAuthStateAt';
|
||||
// The server URL the handoff was started for, round-tripped with the nonce so
|
||||
// the returning token is redeemed against the same (e.g. self-hosted) server.
|
||||
const PREFS_APP_AUTH_SERVER = 'appAuthServer';
|
||||
|
||||
/// True once PowerSync has been reachable for this user at least once
|
||||
/// (i.e. its liveness probe returned 200).
|
||||
const PREFS_HAS_EVER_SYNCED = 'hasEverSynced';
|
||||
|
||||
/// Absolute URL prefix for server-side media files
|
||||
const PREFS_MEDIA_URL_PREFIX = 'mediaUrlPrefix';
|
||||
|
||||
const DEFAULT_ANIMATION_DURATION = Duration(milliseconds: 200);
|
||||
const DEFAULT_ANIMATION_CURVE = Curves.bounceIn;
|
||||
|
||||
@@ -110,8 +140,11 @@ enum EXERCISE_IMAGE_ART_STYLE {
|
||||
OTHER,
|
||||
}
|
||||
|
||||
/// Dummy ID for pseudo meals
|
||||
const PSEUDO_MEAL_ID = -1;
|
||||
/// Sentinel UUID for the synthetic "loose log entries" pseudo-meal.
|
||||
///
|
||||
/// All-zero UUID is reserved by RFC 4122 (the "nil UUID") and won't collide
|
||||
/// with any client-generated UUID v4.
|
||||
const PSEUDO_MEAL_ID = '00000000-0000-0000-0000-000000000000';
|
||||
|
||||
/// Colors used for muscles
|
||||
const COLOR_MAIN_MUSCLES = Colors.red;
|
||||
@@ -132,6 +165,7 @@ const GITHUB_SPONSORS_URL = 'https://github.com/sponsors/wger-project';
|
||||
const GITHUB_ISSUES_MAX_URL_LENGTH = 8000;
|
||||
const DISCORD_URL = 'https://discord.gg/rPWFv6W';
|
||||
const MASTODON_URL = 'https://fosstodon.org/@wger';
|
||||
const READTHEDOCS_URL = 'https://wger.readthedocs.io';
|
||||
const WEBLATE_URL = 'https://hosted.weblate.org/engage/wger';
|
||||
const BUY_ME_A_COFFEE_URL = 'https://buymeacoffee.com/wger';
|
||||
const LIBERAPAY_URL = 'https://liberapay.com/wger';
|
||||
|
||||
@@ -20,28 +20,10 @@ import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_html/flutter_html.dart';
|
||||
import 'package:flutter/painting.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
import 'package:wger/core/exceptions/http_exception.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
import 'package:wger/main.dart';
|
||||
import 'package:wger/models/workouts/log.dart';
|
||||
import 'package:wger/providers/routines.dart';
|
||||
|
||||
import 'consts.dart';
|
||||
import 'logs.dart';
|
||||
|
||||
/// Whether an error dialog is currently on screen.
|
||||
///
|
||||
/// Errors can fire in quick succession; this guards against stacking several
|
||||
/// modal dialogs on top of each other.
|
||||
bool _errorDialogVisible = false;
|
||||
|
||||
/// How an error should be surfaced to the user.
|
||||
enum ErrorSeverity {
|
||||
@@ -55,211 +37,16 @@ enum ErrorSeverity {
|
||||
fatal,
|
||||
}
|
||||
|
||||
void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? context}) {
|
||||
final logger = Logger('showHttpExceptionErrorDialog');
|
||||
|
||||
// Attempt to get the BuildContext from our global navigatorKey.
|
||||
// This allows us to show a dialog even if the error occurs outside
|
||||
// of a widget's build method.
|
||||
final BuildContext? dialogContext = context ?? navigatorKey.currentContext;
|
||||
|
||||
if (dialogContext == null) {
|
||||
if (kDebugMode) {
|
||||
logger.warning('Error: Could not error show http error dialog because the context is null.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_errorDialogVisible) {
|
||||
logger.info('Suppressing error dialog, one is already visible: $exception');
|
||||
return;
|
||||
}
|
||||
_errorDialogVisible = true;
|
||||
|
||||
showDialog(
|
||||
context: dialogContext,
|
||||
builder: (ctx) => AlertDialog(
|
||||
title: Text(AppLocalizations.of(ctx).anErrorOccurred),
|
||||
content: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (exception.type == ErrorType.html)
|
||||
ServerHtmlError(data: exception.htmlError)
|
||||
else
|
||||
...formatApiErrors(extractErrors(exception.errors)),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: Text(MaterialLocalizations.of(ctx).closeButtonLabel),
|
||||
onPressed: () {
|
||||
Navigator.of(ctx).pop();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
).whenComplete(() => _errorDialogVisible = false);
|
||||
}
|
||||
|
||||
void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext? context}) {
|
||||
// Attempt to get the BuildContext from our global navigatorKey.
|
||||
// This allows us to show a dialog even if the error occurs outside
|
||||
// of a widget's build method.
|
||||
final BuildContext? dialogContext = context ?? navigatorKey.currentContext;
|
||||
|
||||
final logger = Logger('showGeneralErrorDialog');
|
||||
|
||||
if (dialogContext == null) {
|
||||
if (kDebugMode) {
|
||||
logger.warning('Error: Could not error show dialog because the context is null.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (_errorDialogVisible) {
|
||||
logger.info('Suppressing error dialog, one is already visible: $error');
|
||||
return;
|
||||
}
|
||||
_errorDialogVisible = true;
|
||||
|
||||
final i18n = AppLocalizations.of(dialogContext);
|
||||
|
||||
// If possible, determine the issue title and message based on the error type.
|
||||
// (Note that issue titles and error messages are not localized)
|
||||
String issueTitle = 'An error occurred';
|
||||
String issueErrorMessage = error.toString();
|
||||
|
||||
if (error is FlutterErrorDetails) {
|
||||
issueTitle = 'Application Error';
|
||||
issueErrorMessage = error.exceptionAsString();
|
||||
} else if (error is MissingRequiredKeysException) {
|
||||
issueTitle = 'Missing Required Key';
|
||||
}
|
||||
|
||||
final String fullStackTrace = stackTrace?.toString() ?? 'No stack trace available.';
|
||||
final applicationLogs = InMemoryLogStore().getFormattedLogs();
|
||||
|
||||
showDialog(
|
||||
context: dialogContext,
|
||||
barrierDismissible: false,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: Row(
|
||||
spacing: 8,
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error, color: Theme.of(context).colorScheme.error),
|
||||
Expanded(
|
||||
child: Text(
|
||||
i18n.anErrorOccurred,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
content: SingleChildScrollView(
|
||||
child: ListBody(
|
||||
children: [
|
||||
Text(i18n.errorInfoDescription),
|
||||
const SizedBox(height: 8),
|
||||
Text(i18n.errorInfoDescription2),
|
||||
const SizedBox(height: 10),
|
||||
ExpansionTile(
|
||||
tilePadding: EdgeInsets.zero,
|
||||
title: Text(i18n.errorViewDetails),
|
||||
children: [
|
||||
Text(
|
||||
issueErrorMessage,
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Container(
|
||||
alignment: Alignment.topLeft,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
constraints: const BoxConstraints(maxHeight: 250),
|
||||
child: SingleChildScrollView(
|
||||
child: Text(
|
||||
fullStackTrace,
|
||||
style: TextStyle(fontSize: 12.0, color: Colors.grey[700]),
|
||||
),
|
||||
),
|
||||
),
|
||||
CopyToClipboardButton(
|
||||
text:
|
||||
'Error Title: $issueTitle\n'
|
||||
'Error Message: $issueErrorMessage\n\n'
|
||||
'Stack Trace:\n$fullStackTrace',
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(i18n.applicationLogs, style: const TextStyle(fontWeight: FontWeight.bold)),
|
||||
Container(
|
||||
alignment: Alignment.topLeft,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
constraints: const BoxConstraints(maxHeight: 250),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
...applicationLogs.map(
|
||||
(entry) => Text(
|
||||
entry,
|
||||
style: TextStyle(fontSize: 12.0, color: Colors.grey[700]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
CopyToClipboardButton(text: applicationLogs.join('\n')),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
child: const Text('Report issue'),
|
||||
onPressed: () async {
|
||||
final githubIssueUrl = buildGithubIssueUrl(
|
||||
issueTitle: issueTitle,
|
||||
issueErrorMessage: issueErrorMessage,
|
||||
stackTrace: fullStackTrace,
|
||||
applicationLogs: applicationLogs,
|
||||
);
|
||||
final Uri reportUri = Uri.parse(githubIssueUrl);
|
||||
|
||||
try {
|
||||
await launchUrl(reportUri, mode: LaunchMode.externalApplication);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
logger.warning('Error launching URL: $e');
|
||||
}
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Error opening issue tracker: $e')));
|
||||
}
|
||||
},
|
||||
),
|
||||
FilledButton(
|
||||
child: Text(MaterialLocalizations.of(context).okButtonLabel),
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
).whenComplete(() => _errorDialogVisible = false);
|
||||
}
|
||||
|
||||
/// Classifies [error] to decide how it should be surfaced.
|
||||
ErrorSeverity classifyError(Object? error) {
|
||||
// Flutter reports layout overflows as a plain FlutterError without a
|
||||
// dedicated type, so matching the message is the only option.
|
||||
final isLayoutOverflow = error is FlutterError && error.toString().contains('overflowed');
|
||||
|
||||
if (error is NetworkImageLoadException || isLayoutOverflow) {
|
||||
// A failed network image load as a plain StateError
|
||||
final isImageLoadFailure = error is StateError && error.toString().contains('Failed to load');
|
||||
|
||||
if (error is NetworkImageLoadException || isLayoutOverflow || isImageLoadFailure) {
|
||||
return ErrorSeverity.cosmetic;
|
||||
}
|
||||
if (error is SocketException || error is http.ClientException || error is TimeoutException) {
|
||||
@@ -268,44 +55,14 @@ ErrorSeverity classifyError(Object? error) {
|
||||
return ErrorSeverity.fatal;
|
||||
}
|
||||
|
||||
/// Routes [error] to the appropriate UI based on its [ErrorSeverity].
|
||||
///
|
||||
/// The caller is responsible for logging the error beforehand.
|
||||
void handleError(Object? error, StackTrace? stackTrace) {
|
||||
switch (classifyError(error)) {
|
||||
case ErrorSeverity.cosmetic:
|
||||
break;
|
||||
case ErrorSeverity.transient:
|
||||
showTransientErrorSnackbar();
|
||||
case ErrorSeverity.fatal:
|
||||
if (error is WgerHttpException) {
|
||||
showHttpExceptionErrorDialog(error);
|
||||
} else {
|
||||
showGeneralErrorDialog(error, stackTrace);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a brief, non-blocking snackbar telling the user about a (hopefully)
|
||||
/// transient error such as network problems, etc.
|
||||
void showTransientErrorSnackbar() {
|
||||
final messenger = scaffoldMessengerKey.currentState;
|
||||
final context = navigatorKey.currentContext;
|
||||
|
||||
if (messenger == null || context == null) {
|
||||
if (kDebugMode) {
|
||||
Logger(
|
||||
'showNetworkErrorSnackbar',
|
||||
).warning('Could not show snackbar: no messenger or context available.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
messenger
|
||||
..clearSnackBars()
|
||||
..showSnackBar(
|
||||
SnackBar(content: Text(AppLocalizations.of(context).errorCouldNotConnectToServer)),
|
||||
);
|
||||
/// True if [e] means "the server can't be reached right now", as opposed to
|
||||
/// an HTTP response we got but didn't like (e.g. a 401, which means the token
|
||||
/// is invalid)
|
||||
bool isNetworkError(Object e) {
|
||||
return e is http.ClientException ||
|
||||
e is SocketException ||
|
||||
e is HandshakeException ||
|
||||
e is TimeoutException;
|
||||
}
|
||||
|
||||
/// Builds the URL that opens a pre-filled GitHub bug report.
|
||||
@@ -347,111 +104,6 @@ String buildGithubIssueUrl({
|
||||
}
|
||||
}
|
||||
|
||||
/// A widget to render HTML errors returned by the server
|
||||
///
|
||||
/// This is a simple wrapper around the `Html` Widget, with some light changes
|
||||
/// to the style.
|
||||
class ServerHtmlError extends StatelessWidget {
|
||||
final logger = Logger('ServerHtml');
|
||||
final String data;
|
||||
|
||||
ServerHtmlError({required this.data, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Html(
|
||||
data: data,
|
||||
style: {
|
||||
'h1': Style(fontSize: FontSize(theme.textTheme.bodyLarge?.fontSize ?? 15)),
|
||||
'h2': Style(fontSize: FontSize(theme.textTheme.bodyMedium?.fontSize ?? 15)),
|
||||
},
|
||||
doNotRenderTheseTags: const {'a'},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CopyToClipboardButton extends StatelessWidget {
|
||||
final logger = Logger('CopyToClipboardButton');
|
||||
final String text;
|
||||
|
||||
CopyToClipboardButton({required this.text, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final i18n = AppLocalizations.of(context);
|
||||
|
||||
return TextButton.icon(
|
||||
icon: const Icon(Icons.copy_all_outlined, size: 18),
|
||||
label: Text(i18n.copyToClipboard),
|
||||
style: TextButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: text))
|
||||
.then((_) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('Details copied to clipboard!')));
|
||||
}
|
||||
})
|
||||
.catchError((copyError) {
|
||||
logger.warning('Error copying to clipboard: $copyError');
|
||||
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(const SnackBar(content: Text('Could not copy details.')));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void showDeleteDialog(BuildContext context, String confirmDeleteName, Log log) async {
|
||||
final res = await showDialog(
|
||||
context: context,
|
||||
builder: (BuildContext contextDialog) {
|
||||
return AlertDialog(
|
||||
content: Text(AppLocalizations.of(context).confirmDelete(confirmDeleteName)),
|
||||
actions: [
|
||||
TextButton(
|
||||
key: const ValueKey('cancel-button'),
|
||||
child: Text(MaterialLocalizations.of(context).cancelButtonLabel),
|
||||
onPressed: () => Navigator.of(contextDialog).pop(),
|
||||
),
|
||||
TextButton(
|
||||
key: const ValueKey('delete-button'),
|
||||
child: Text(
|
||||
AppLocalizations.of(context).delete,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
onPressed: () {
|
||||
context.read<RoutinesProvider>().deleteLog(log.id!, log.routineId);
|
||||
|
||||
Navigator.of(contextDialog).pop();
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
AppLocalizations.of(context).successfullyDeleted,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
return res;
|
||||
}
|
||||
|
||||
class ApiError {
|
||||
final String key;
|
||||
late List<String> errorMessages = [];
|
||||
@@ -503,85 +155,3 @@ String _formatHeader(String key) {
|
||||
header = header.replaceAll('_', ' ');
|
||||
return header.replaceAll('.', ' ');
|
||||
}
|
||||
|
||||
/// Processes the error messages from the server and returns a list of widgets
|
||||
List<Widget> formatApiErrors(List<ApiError> errors, {Color? color}) {
|
||||
final logger = Logger('formatApiErrors');
|
||||
final textColor = color ?? Colors.black;
|
||||
|
||||
final List<Widget> errorList = [];
|
||||
|
||||
for (final error in errors) {
|
||||
errorList.add(
|
||||
Text(
|
||||
error.key,
|
||||
style: TextStyle(fontWeight: FontWeight.bold, color: textColor),
|
||||
),
|
||||
);
|
||||
|
||||
logger.warning(error.errorMessages);
|
||||
for (final message in error.errorMessages) {
|
||||
errorList.add(Text(message, style: TextStyle(color: textColor)));
|
||||
}
|
||||
errorList.add(const SizedBox(height: 8));
|
||||
}
|
||||
|
||||
return errorList;
|
||||
}
|
||||
|
||||
/// Processes the error messages from the server and returns a list of widgets
|
||||
List<Widget> formatTextErrors(List<String> errors, {String? title, Color? color}) {
|
||||
final textColor = color ?? Colors.black;
|
||||
|
||||
final List<Widget> errorList = [];
|
||||
|
||||
if (title != null) {
|
||||
errorList.add(
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(fontWeight: FontWeight.bold, color: textColor),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
for (final message in errors) {
|
||||
errorList.add(Text(message, style: TextStyle(color: textColor)));
|
||||
}
|
||||
errorList.add(const SizedBox(height: 8));
|
||||
|
||||
return errorList;
|
||||
}
|
||||
|
||||
class FormHttpErrorsWidget extends StatelessWidget {
|
||||
final WgerHttpException exception;
|
||||
|
||||
const FormHttpErrorsWidget(this.exception, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Container(
|
||||
constraints: const BoxConstraints(maxHeight: 250),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: theme.colorScheme.error, width: 1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: theme.colorScheme.error),
|
||||
if (exception.type == ErrorType.html)
|
||||
ServerHtmlError(data: exception.htmlError)
|
||||
else
|
||||
...formatApiErrors(
|
||||
extractErrors(exception.errors),
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
68
lib/helpers/form_validators.dart
Normal file
68
lib/helpers/form_validators.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* 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:intl/intl.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
/// Validates an optional decimal text field.
|
||||
///
|
||||
/// Empty input is allowed and returns `null`. Non-empty input must be
|
||||
/// parseable by [numberFormat]; otherwise an `enterValidNumber` error
|
||||
/// message is returned. When [max] is set, the value must also be within
|
||||
/// `0..max` (inclusive).
|
||||
String? validateOptionalDecimal(
|
||||
String? text,
|
||||
NumberFormat numberFormat,
|
||||
BuildContext context, {
|
||||
num? max,
|
||||
}) {
|
||||
final trimmed = (text ?? '').trim();
|
||||
if (trimmed.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final parsed = numberFormat.tryParse(trimmed);
|
||||
if (parsed == null) {
|
||||
return AppLocalizations.of(context).enterValidNumber;
|
||||
}
|
||||
if (max != null && (parsed < 0 || parsed > max)) {
|
||||
return AppLocalizations.of(context).formMinMaxValues(0, max.toInt());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Validates an optional whole-number field. Empty input is allowed and returns
|
||||
/// `null`; otherwise the value must be an integer within [min]..[max] inclusive.
|
||||
String? validateOptionalIntegerInRange(
|
||||
String? value,
|
||||
int min,
|
||||
int max,
|
||||
AppLocalizations i18n,
|
||||
) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
final parsed = int.tryParse(value);
|
||||
if (parsed == null) {
|
||||
return i18n.enterValidNumber;
|
||||
}
|
||||
if (parsed < min || parsed > max) {
|
||||
return i18n.formMinMaxValues(min, max);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
55
lib/helpers/jwt.dart
Normal file
55
lib/helpers/jwt.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* 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.
|
||||
*
|
||||
* 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:convert';
|
||||
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
final _logger = Logger('jwt');
|
||||
|
||||
/// Decodes the payload (middle segment) of a JWT.
|
||||
///
|
||||
/// Returns null when the input is not a three-segment token, when the middle
|
||||
/// segment is not valid base64-url, or when the decoded bytes are not a JSON
|
||||
/// object. The signature is not verified, so callers must treat the result
|
||||
/// as untrusted data.
|
||||
Map<String, dynamic>? decodeJwtPayload(String jwt) {
|
||||
try {
|
||||
final parts = jwt.split('.');
|
||||
if (parts.length != 3) {
|
||||
return null;
|
||||
}
|
||||
return json.decode(utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))))
|
||||
as Map<String, dynamic>;
|
||||
} catch (e) {
|
||||
_logger.warning('Could not decode JWT payload', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Extracts the `exp` claim (unix seconds) as a UTC [DateTime].
|
||||
///
|
||||
/// Returns null when the payload is null, when `exp` is missing, or when it is
|
||||
/// not numeric. Fractional seconds are truncated.
|
||||
DateTime? jwtExp(Map<String, dynamic>? payload) {
|
||||
final exp = payload?['exp'];
|
||||
if (exp is! num) {
|
||||
return null;
|
||||
}
|
||||
return DateTime.fromMillisecondsSinceEpoch(exp.toInt() * 1000, isUtc: true);
|
||||
}
|
||||
@@ -32,7 +32,9 @@ extension MeasurementChartEntryListExtensions on List<MeasurementChartEntry> {
|
||||
// this also helps with computing delta's across the entire window
|
||||
List<MeasurementChartEntry> whereDateWithInterpolation(DateTime start, DateTime? end) {
|
||||
// Make sure our list is sorted by date
|
||||
sort((a, b) => a.date.compareTo(b.date));
|
||||
// Avoid mutating the original list (it may be unmodifiable/const). Work on a copy.
|
||||
final List<MeasurementChartEntry> sorted = [...this];
|
||||
sorted.sort((a, b) => a.date.compareTo(b.date));
|
||||
|
||||
// Initialize result list
|
||||
final List<MeasurementChartEntry> result = [];
|
||||
@@ -46,7 +48,7 @@ extension MeasurementChartEntryListExtensions on List<MeasurementChartEntry> {
|
||||
MeasurementChartEntry? lastBeforeEnd;
|
||||
|
||||
// Single pass through the data
|
||||
for (final entry in this) {
|
||||
for (final entry in sorted) {
|
||||
if (entry.date.isSameDayAs(start)) {
|
||||
hasEntryOnStartDay = true;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (C) 2020, 2021 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.
|
||||
@@ -19,10 +19,15 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
void launchURL(String url, BuildContext context) async {
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
final launched = await launchUrl(Uri.parse(url));
|
||||
void launchURL(
|
||||
String url,
|
||||
BuildContext context, {
|
||||
LaunchMode mode = LaunchMode.platformDefault,
|
||||
}) async {
|
||||
final launched = await launchUrl(Uri.parse(url), mode: mode);
|
||||
|
||||
if (!launched) {
|
||||
final scaffoldMessenger = ScaffoldMessenger.of(context);
|
||||
scaffoldMessenger.showSnackBar(
|
||||
SnackBar(content: Text('Could not open $url.')),
|
||||
);
|
||||
|
||||
81
lib/helpers/number_input.dart
Normal file
81
lib/helpers/number_input.dart
Normal file
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* 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/services.dart';
|
||||
|
||||
/// A [TextInputFormatter] for non-negative decimal numbers.
|
||||
///
|
||||
/// A numeric keyboard cannot be pinned to a locale, so a user may only be able
|
||||
/// to type '.' even when the locale expects ','. This formatter accepts both
|
||||
/// '.' and ',' and rewrites the separator to [decimalSeparator], so the field
|
||||
/// content always matches the active locale and parses correctly with
|
||||
/// `NumberFormat.parse`. Digits are kept, at most one separator is allowed,
|
||||
/// at most [maxDecimalPlaces] digits are kept after it, and every other
|
||||
/// character (grouping separators, spaces, letters) is dropped.
|
||||
class LocalizedDecimalInputFormatter extends TextInputFormatter {
|
||||
LocalizedDecimalInputFormatter(this.decimalSeparator, {this.maxDecimalPlaces = 2});
|
||||
|
||||
/// Decimal separator of the active locale, e.g. obtained from
|
||||
/// `NumberFormat.decimalPattern(locale).symbols.DECIMAL_SEP`.
|
||||
final String decimalSeparator;
|
||||
|
||||
/// Maximum digits kept after the separator; extra fractional digits are
|
||||
/// dropped, mirroring the backend's `decimal_places`.
|
||||
final int maxDecimalPlaces;
|
||||
|
||||
@override
|
||||
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
|
||||
final text = newValue.text;
|
||||
final filtered = _filter(text);
|
||||
|
||||
final base = newValue.selection.baseOffset;
|
||||
final cursor = (base < 0 || base > text.length)
|
||||
? filtered.length
|
||||
: _filter(text.substring(0, base)).length;
|
||||
|
||||
return TextEditingValue(
|
||||
text: filtered,
|
||||
selection: TextSelection.collapsed(offset: cursor),
|
||||
);
|
||||
}
|
||||
|
||||
String _filter(String input) {
|
||||
const digits = '0123456789';
|
||||
final buffer = StringBuffer();
|
||||
var hasSeparator = false;
|
||||
var decimals = 0;
|
||||
for (var i = 0; i < input.length; i++) {
|
||||
final char = input[i];
|
||||
if (digits.contains(char)) {
|
||||
if (hasSeparator) {
|
||||
if (decimals >= maxDecimalPlaces) {
|
||||
continue;
|
||||
}
|
||||
decimals++;
|
||||
}
|
||||
buffer.write(char);
|
||||
} else if (char == '.' || char == ',') {
|
||||
if (!hasSeparator) {
|
||||
buffer.write(decimalSeparator);
|
||||
hasSeparator = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
53
lib/helpers/routines/validators.dart
Normal file
53
lib/helpers/routines/validators.dart
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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:wger/l10n/generated/app_localizations.dart';
|
||||
|
||||
/// Cross-field validation for a workout log entry, mirroring the
|
||||
/// reachable part of the backend `WorkoutLog.clean()` rule: at least
|
||||
/// one of [repetitions] or [weight] must be set.
|
||||
String? validateWorkoutLogCrossField({
|
||||
required num? repetitions,
|
||||
required num? weight,
|
||||
required AppLocalizations i18n,
|
||||
}) {
|
||||
if (repetitions == null && weight == null) {
|
||||
return i18n.weightOrRepsRequired;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Cross-field validation for a workout session, mirroring the backend
|
||||
/// `WorkoutSession.clean()` rules:
|
||||
///
|
||||
/// - [timeStart] and [timeEnd] must both be set or both be empty,
|
||||
/// - if both are set, [timeStart] must not be after [timeEnd].
|
||||
String? validateWorkoutSessionTimes({
|
||||
required TimeOfDay? timeStart,
|
||||
required TimeOfDay? timeEnd,
|
||||
required AppLocalizations i18n,
|
||||
}) {
|
||||
if ((timeStart == null) != (timeEnd == null)) {
|
||||
return i18n.timeStartEndBothOrNeither;
|
||||
}
|
||||
if (timeStart != null && timeEnd != null && timeStart.isAfter(timeEnd)) {
|
||||
return i18n.timeStartAhead;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -878,7 +878,6 @@
|
||||
"errorViewDetails": "التفاصيل التقنية",
|
||||
"applicationLogs": "سجلات التطبيق",
|
||||
"errorCouldNotConnectToServer": "لم يتمكن التطبيق من الاتصال بالخادم",
|
||||
"errorCouldNotConnectToServerDetails": "لم يتمكن التطبيق من الاتصال بالخادم. يرجى التحقق من اتصالك بالإنترنت أو عنوان URL الخاص بالخادم، ثم المحاولة مرة أخرى. إذا استمرت المشكلة، فاتصل بمسؤول الخادم.",
|
||||
"max": "الاقصى",
|
||||
"min": "الادنى",
|
||||
"chartDuringPlanTitle": "{chartName} خلال الخطة الغذائية {planName}",
|
||||
|
||||
@@ -917,7 +917,6 @@
|
||||
"errorViewDetails": "Detalls tècnics",
|
||||
"applicationLogs": "Registres de l'aplicació",
|
||||
"errorCouldNotConnectToServer": "No s'ha pogut connectar al servidor",
|
||||
"errorCouldNotConnectToServerDetails": "L'aplicació no s'ha pogut connectar al servidor. Comprova la teva connexió a internet, o la URL del servidor i torna-ho a intentar. Si el problema persisteix, contacta amb l'administrador.",
|
||||
"copyToClipboard": "Copia al porta-retalls",
|
||||
"min": "Mínim",
|
||||
"max": "Màxim",
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
"@reset": {
|
||||
"description": "Button text allowing the user to reset the entered values to the default"
|
||||
},
|
||||
"customServerHint": "Geben Sie die Adresse deines eigenen Servers ein, ansonsten wird die Standardadresse verwendet",
|
||||
"customServerHint": "Gebe die Adresse deines eigenen Servers ein, ansonsten wird die Standardadresse verwendet",
|
||||
"@customServerHint": {
|
||||
"description": "Hint text for the form where the users can enter their own wger instance"
|
||||
},
|
||||
@@ -558,6 +558,7 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"enterMaxCharacters": "Bitte gebe höchstens {max} Zeichen ein",
|
||||
"baseNameEnglish": "Alle Übungen brauchen einen Basisnamen in Englisch",
|
||||
"contributeExerciseWarning": "Sie können nur Übungen beitragen, wenn Ihr Konto älter als {days} Tage ist und Sie Ihre E-Mail verifiziert haben",
|
||||
"@contributeExerciseWarning": {
|
||||
@@ -641,8 +642,11 @@
|
||||
"aboutDonateTitle": "Mach eine Spende",
|
||||
"aboutDonateText": "Das Projekt ist kostenlos und wird es auch bleiben, der Betrieb des Servers hingegen ist es nicht! Die Entwicklung erfordert zudem viel Zeit und Mühe von Freiwilligen. Ihr Beitrag deckt diese Kosten direkt und trägt zur Zuverlässigkeit des Dienstes bei.",
|
||||
"settingsCacheTitle": "Zwischenspeicher",
|
||||
"settingsExerciseCacheDescription": "Übungs-Zwischenspeicher",
|
||||
"settingsImageCacheDescription": "Bild-Zwischenspeicher",
|
||||
"settingsCacheDeletedSnackbar": "Zwischenspeicher erfolgreich gelöscht",
|
||||
"settingsDataTitle": "Datenschutz",
|
||||
"settingsKeepDataOnLogout": "Daten beim Abmelden behalten",
|
||||
"settingsKeepDataOnLogoutDescription": "Die lokale Datenbank bleibt auf dem Gerät, bis sich ein anderes Konto anmeldet.",
|
||||
"lb": "lb",
|
||||
"@lb": {
|
||||
"description": "Generated entry for translation for server strings"
|
||||
@@ -836,7 +840,6 @@
|
||||
"themeMode": "Theme Modus",
|
||||
"lightMode": "Immer Hellmodus",
|
||||
"systemMode": "Systemeinstellungen",
|
||||
"errorCouldNotConnectToServerDetails": "Die Anwendung konnte keine Verbindung zum Server herstellen. Bitte überprüfen Sie Ihre Internetverbindung oder die Server-URL und versuchen Sie es erneut. Sollte das Problem weiterhin bestehen, wenden Sie sich an den Serveradministrator.",
|
||||
"fitInWeek": "Fester Wochenrhythmus",
|
||||
"fitInWeekHelp": "Wenn diese Option aktiviert ist, wiederholen sich die Tage in einem wöchentlichen Zyklus, andernfalls folgen die Tage der Reihe nach, ohne Rücksicht auf den Beginn einer neuen Woche.",
|
||||
"aboutContributeText": "Beiträge aller Art sind willkommen. Egal, ob Sie Entwickler, Übersetzer oder einfach nur Fitnessbegeisterter sind – jede Unterstützung ist willkommen!",
|
||||
@@ -1003,6 +1006,8 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"weightOrRepsRequired": "Bitte Gewicht, Wiederholungen oder beides eingeben",
|
||||
"timeStartEndBothOrNeither": "Entweder Start- und Endzeit beide setzen oder beide leer lassen",
|
||||
"personalRecords": "Persönliche Rekorde",
|
||||
"noTrophies": "Du hast noch keine Trophäen",
|
||||
"preview": "Vorschau",
|
||||
|
||||
@@ -13,14 +13,6 @@
|
||||
"@register": {
|
||||
"description": "Text for registration button"
|
||||
},
|
||||
"useDefaultServer": "Use default server",
|
||||
"@useDefaultServer": {
|
||||
"description": "Toggle button allowing users to switch between the default and a custom wger server"
|
||||
},
|
||||
"useCustomServer": "Use custom server",
|
||||
"@useCustomServer": {
|
||||
"description": "Toggle button allowing users to switch between the default and a custom wger server"
|
||||
},
|
||||
"invalidUrl": "Please enter a valid URL",
|
||||
"@invalidUrl": {
|
||||
"description": "Error message when the user enters an invalid URL, e.g. in the login form"
|
||||
@@ -56,17 +48,63 @@
|
||||
"@invalidUsername": {
|
||||
"description": "Error message when the user enters an invalid username"
|
||||
},
|
||||
"useApiToken": "Use API Token",
|
||||
"useUsernameAndPassword": "Use username and password",
|
||||
"apiToken": "API Token",
|
||||
"@apiToken": {},
|
||||
"invalidApiToken": "Please enter a valid API key",
|
||||
"@invalidApiToken": {
|
||||
"description": "Error message when the user enters an invalid API key"
|
||||
"refreshToken": "Refresh token",
|
||||
"@refreshToken": {},
|
||||
"invalidRefreshToken": "Please enter a valid refresh token",
|
||||
"@invalidRefreshToken": {
|
||||
"description": "Error message when the user enters an invalid refresh token"
|
||||
},
|
||||
"apiTokenValidChars": "An API key may only contain the letters a-f, numbers 0-9 and be exactly 40 characters long",
|
||||
"@apiTokenValidChars": {
|
||||
"description": "Error message when the user tries to input a API key with forbidden characters"
|
||||
"refreshTokenValidChars": "A refresh token has three dot-separated segments (header.payload.signature), each made of letters, digits, '-' and '_'",
|
||||
"@refreshTokenValidChars": {
|
||||
"description": "Error message when the user pastes a string that does not match the JWT shape"
|
||||
},
|
||||
"refreshTokenHelperText": "Generate a JWT refresh token on the wger website and paste it here. Useful when your server sits behind an auth proxy or when you want to skip the regular login flow.",
|
||||
"@refreshTokenHelperText": {
|
||||
"description": "Helper text on the refresh-token paste field"
|
||||
},
|
||||
"mfaChallengeTitle": "Two-factor authentication",
|
||||
"@mfaChallengeTitle": {
|
||||
"description": "App bar title on the 2FA challenge screen"
|
||||
},
|
||||
"mfaChallengeTotpPrompt": "Enter the 6-digit code from your authenticator app",
|
||||
"@mfaChallengeTotpPrompt": {
|
||||
"description": "Helper text above the TOTP input field"
|
||||
},
|
||||
"mfaChallengeRecoveryPrompt": "Enter one of your recovery codes",
|
||||
"@mfaChallengeRecoveryPrompt": {
|
||||
"description": "Helper text above the recovery-code input field"
|
||||
},
|
||||
"mfaCodeLabel": "Code",
|
||||
"@mfaCodeLabel": {
|
||||
"description": "Label on the 2FA code input field"
|
||||
},
|
||||
"mfaInvalidCode": "Please enter a code",
|
||||
"@mfaInvalidCode": {
|
||||
"description": "Validation error when the 2FA code field is empty"
|
||||
},
|
||||
"mfaUseRecoveryCode": "Use a recovery code instead",
|
||||
"@mfaUseRecoveryCode": {
|
||||
"description": "Button that switches the 2FA challenge to recovery-code mode"
|
||||
},
|
||||
"mfaUseTotpCode": "Use an authenticator app code",
|
||||
"@mfaUseTotpCode": {
|
||||
"description": "Button that switches the 2FA challenge back to TOTP mode"
|
||||
},
|
||||
"mfaSubmit": "Verify",
|
||||
"@mfaSubmit": {
|
||||
"description": "Submit button on the 2FA challenge screen"
|
||||
},
|
||||
"mfaUnsupportedFactor": "Your account is set up with a second factor this app does not support yet. Please sign in on the website.",
|
||||
"@mfaUnsupportedFactor": {
|
||||
"description": "Shown when the server reports only factor types the app cannot handle (e.g. webauthn)"
|
||||
},
|
||||
"manageAccountOnWeb": "Manage account on the web",
|
||||
"@manageAccountOnWeb": {
|
||||
"description": "Label on a button that opens the user's preferences page on the wger website"
|
||||
},
|
||||
"manageAccountOnWebSubtitle": "Change your password, set up two-factor authentication, manage API tokens, or delete your account.",
|
||||
"@manageAccountOnWebSubtitle": {
|
||||
"description": "Helper text below the 'Manage account on the web' button listing what is configurable there"
|
||||
},
|
||||
"customServerUrl": "URL of the wger instance",
|
||||
"@customServerUrl": {
|
||||
@@ -80,10 +118,36 @@
|
||||
"@reset": {
|
||||
"description": "Button text allowing the user to reset the entered values to the default"
|
||||
},
|
||||
"registerInstead": "Don't have an account? Register now",
|
||||
"@registerInstead": {},
|
||||
"loginInstead": "Already have an account? Login",
|
||||
"@loginInstead": {},
|
||||
"advanced": "Advanced",
|
||||
"@advanced": {},
|
||||
"advancedSubtitle": "Server and authentication options",
|
||||
"@advancedSubtitle": {},
|
||||
"serverSectionLabel": "Server",
|
||||
"@serverSectionLabel": {},
|
||||
"signInMethodSectionLabel": "Sign-in method",
|
||||
"@signInMethodSectionLabel": {},
|
||||
"serverOptionDefaultDetail": "The official server",
|
||||
"@serverOptionDefaultDetail": {},
|
||||
"serverOptionSelfHostedTitle": "Self-hosted",
|
||||
"@serverOptionSelfHostedTitle": {},
|
||||
"serverOptionSelfHostedDetail": "Connect to your own instance",
|
||||
"@serverOptionSelfHostedDetail": {},
|
||||
"authOptionPasswordTitle": "Username and password",
|
||||
"@authOptionPasswordTitle": {},
|
||||
"signInWithToken": "Sign in with token",
|
||||
"@signInWithToken": {},
|
||||
"tokenSubtitle": "Generate one on the wger website",
|
||||
"@tokenSubtitle": {},
|
||||
"newToWger": "New to wger?",
|
||||
"@newToWger": {},
|
||||
"alreadyHaveAccount": "Already have an account?",
|
||||
"@alreadyHaveAccount": {},
|
||||
"tokenLabel": "Token",
|
||||
"@tokenLabel": {},
|
||||
"webHandoffLinkLabel": "Other sign-in options",
|
||||
"@webHandoffLinkLabel": {},
|
||||
"webHandoffLinkSubtitle": "Social login, passkey, SSO",
|
||||
"@webHandoffLinkSubtitle": {},
|
||||
"labelBottomNavWorkout": "Workout",
|
||||
"@labelBottomNavWorkout": {
|
||||
"description": "Label used in bottom navigation, use a short word"
|
||||
@@ -139,7 +203,6 @@
|
||||
"@noMatchingExerciseFound": {
|
||||
"description": "Message returned if no exercises match the searched string"
|
||||
},
|
||||
"searchNamesInEnglish": "Also search for names in English",
|
||||
"equipment": "Equipment",
|
||||
"@equipment": {
|
||||
"description": "Equipment needed to perform an exercise"
|
||||
@@ -239,8 +302,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"sameRepetitions": "If you do the same repetitions and weight for all sets you can just fill in one row. For example for 4 sets just enter 10 for the repetitions, this automatically becomes \"4 x 10\".",
|
||||
"@sameRepetitions": {},
|
||||
"comment": "Comment",
|
||||
"@comment": {
|
||||
"description": "Comment, additional information"
|
||||
@@ -283,8 +344,6 @@
|
||||
"@newSet": {
|
||||
"description": "Header when adding a new set to a workout day"
|
||||
},
|
||||
"selectExercises": "If you want to do a superset you can search for several exercises, they will be grouped together",
|
||||
"@selectExercises": {},
|
||||
"personalRecords": "Personal records",
|
||||
"gymMode": "Gym mode",
|
||||
"@gymMode": {
|
||||
@@ -366,7 +425,7 @@
|
||||
"@logIngredient": {},
|
||||
"searchIngredient": "Search ingredient",
|
||||
"@searchIngredient": {
|
||||
"description": "Label on ingredient search form"
|
||||
"description": "Label (or Hint text) on ingredient search form"
|
||||
},
|
||||
"nutritionalPlan": "Nutritional plan",
|
||||
"@nutritionalPlan": {},
|
||||
@@ -378,6 +437,14 @@
|
||||
"@noNutritionalPlans": {
|
||||
"description": "Message shown when the user has no nutritional plans"
|
||||
},
|
||||
"clearSearchTerm": "Clear search term (text)",
|
||||
"@clearSearchTerm": {
|
||||
"description": "Tooltip for the icon-button that clears the ingredient search text field"
|
||||
},
|
||||
"ingredients": "Ingredients",
|
||||
"@ingredients": {
|
||||
"description": "Plural title for the ingredients overview screen"
|
||||
},
|
||||
"onlyLogging": "Only track calories",
|
||||
"onlyLoggingHelpText": "Check the box if you only want to log your calories and don't want to setup a detailed nutritional plan with specific meals",
|
||||
"goalMacro": "Macro goals",
|
||||
@@ -399,12 +466,15 @@
|
||||
"goalFat": "Fat goal",
|
||||
"goalFiber": "Fiber goal",
|
||||
"anErrorOccurred": "An Error Occurred!",
|
||||
"errorRawSource": "Raw",
|
||||
"@errorRawSource": {
|
||||
"description": "Tab label for showing an HTML error response in its raw (unrendered) form, opposite of 'Preview'."
|
||||
},
|
||||
"errorInfoDescription": "We're sorry, but something went wrong. You can help us fix this by reporting the issue on GitHub.",
|
||||
"errorInfoDescription2": "You can continue using the app, but some features may not work.",
|
||||
"errorViewDetails": "Technical details",
|
||||
"applicationLogs": "Application logs",
|
||||
"errorCouldNotConnectToServer": "Couldn't connect to server",
|
||||
"errorCouldNotConnectToServerDetails": "The application could not connect to the server. Please check your internet connection or the server URL and try again. If the problem persists, contact the server administrator.",
|
||||
"copyToClipboard": "Copy to clipboard",
|
||||
"weight": "Weight",
|
||||
"min": "Min",
|
||||
@@ -490,7 +560,9 @@
|
||||
"timeStartAhead": "Start time cannot be ahead of end time",
|
||||
"@timeStartAhead": {},
|
||||
"ingredient": "Ingredient",
|
||||
"@ingredient": {},
|
||||
"@ingredient": {
|
||||
"description": "Singular label for an ingredient"
|
||||
},
|
||||
"energy": "Energy",
|
||||
"@energy": {
|
||||
"description": "Energy in a meal, ingredient etc. e.g. in kJ"
|
||||
@@ -499,6 +571,7 @@
|
||||
"@energyShort": {
|
||||
"description": "The first letter or short name of the word 'Energy', used in overviews"
|
||||
},
|
||||
"dietaryInformation": "Dietary information",
|
||||
"macronutrients": "Macronutrients",
|
||||
"@macronutrients": {},
|
||||
"planned": "Planned",
|
||||
@@ -619,10 +692,6 @@
|
||||
"@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"
|
||||
@@ -630,10 +699,6 @@
|
||||
"edit": "Edit",
|
||||
"@edit": {},
|
||||
"preview": "Preview",
|
||||
"loadingText": "Loading...",
|
||||
"@loadingText": {
|
||||
"description": "Text to show when entries are being loaded in the background: Loading..."
|
||||
},
|
||||
"delete": "Delete",
|
||||
"@delete": {},
|
||||
"confirmDelete": "Are you sure you want to delete '{toDelete}'?",
|
||||
@@ -670,13 +735,11 @@
|
||||
"aboutJoinCommunityTitle": "Join the community",
|
||||
"aboutMastodonTitle": "Mastodon",
|
||||
"aboutDiscordTitle": "Discord",
|
||||
"aboutViewDocsTitle": "Open documentation",
|
||||
"aboutViewLicensesTitle": "View licenses",
|
||||
"others": "Others",
|
||||
"calendar": "Calendar",
|
||||
"@calendar": {},
|
||||
"goToToday": "Go to today",
|
||||
"@goToToday": {
|
||||
"description": "Label on button to jump back to 'today' in the calendar widget"
|
||||
},
|
||||
"enterValue": "Please enter a value",
|
||||
"@enterValue": {
|
||||
"description": "Error message when the user hasn't entered a value on a required field"
|
||||
@@ -722,6 +785,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"enterMaxCharacters": "Please enter at most {max} characters",
|
||||
"@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"
|
||||
}
|
||||
}
|
||||
},
|
||||
"baseNameEnglish": "All exercises need a base name in English",
|
||||
"nrOfSets": "Sets per exercise: {nrOfSets}",
|
||||
"@nrOfSets": {
|
||||
@@ -733,11 +806,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"setUnitsAndRir": "Set units and RiR",
|
||||
"@setUnitsAndRir": {
|
||||
"description": "Label shown on the slider where the user can toggle showing units and RiR",
|
||||
"type": "text"
|
||||
},
|
||||
"enterValidNumber": "Please enter a valid number",
|
||||
"@enterValidNumber": {
|
||||
"description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')"
|
||||
@@ -786,6 +854,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"powerSyncUnreachableTitle": "Sync service unreachable",
|
||||
"powerSyncUnreachableContent": "Your wger server is reachable, but the (separate) service that handles offline sync is not responding. If you self-host wger, check your configuration and make sure the PowerSync service is running correctly.",
|
||||
"serverUnreachableRetry": "Try again",
|
||||
"@serverUnreachableRetry": {
|
||||
"description": "Button that re-runs the auto-login attempt against the saved server."
|
||||
},
|
||||
"productFound": "Product found",
|
||||
"@productFound": {
|
||||
"description": "Header label for dialog when product is found with barcode"
|
||||
@@ -914,7 +988,6 @@
|
||||
},
|
||||
"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": {
|
||||
@@ -935,8 +1008,6 @@
|
||||
"fitInWeekHelp": "If enabled, the days will repeat in a weekly cycle, otherwise the days will follow sequentially without regards to the start of a new week.",
|
||||
"addSuperset": "Add superset",
|
||||
"superset": "Superset",
|
||||
"setHasProgression": "Set has progression",
|
||||
"setHasProgressionWarning": "Please note that at the moment it is not possible to edit all settings for a set on the mobile application or configure automatic progression. For now, please use the web application.",
|
||||
"setHasNoExercises": "This set has no exercises yet!",
|
||||
"contributeExercise": "Contribute an exercise",
|
||||
"translation": "Translation",
|
||||
@@ -955,9 +1026,11 @@
|
||||
"enterTextInLanguage": "Please enter the text in the correct language!",
|
||||
"settingsTitle": "Settings",
|
||||
"settingsCacheTitle": "Cache",
|
||||
"settingsExerciseCacheDescription": "Exercise cache",
|
||||
"settingsIngredientCacheDescription": "Ingredient cache",
|
||||
"settingsImageCacheDescription": "Image cache",
|
||||
"settingsCacheDeletedSnackbar": "Cache successfully cleared",
|
||||
"settingsDataTitle": "Privacy",
|
||||
"settingsKeepDataOnLogout": "Keep data when logging out",
|
||||
"settingsKeepDataOnLogoutDescription": "The local database stays on your device until a different account signs in.",
|
||||
"aboutPageTitle": "About us & Support",
|
||||
"contributeExerciseWarning": "You can only contribute exercises if your account is older than {days} days and have verified your email",
|
||||
"@contributeExerciseWarning": {
|
||||
@@ -1168,6 +1241,7 @@
|
||||
"darkMode": "Always dark mode",
|
||||
"lightMode": "Always light mode",
|
||||
"systemMode": "System settings",
|
||||
"youAreOffline": "You are offline",
|
||||
"appLanguage": "App language",
|
||||
"@appLanguage": {
|
||||
"description": "Label for the in-app language selector in settings"
|
||||
@@ -1218,21 +1292,58 @@
|
||||
"@searchLanguageAll": {
|
||||
"description": "Label used in the language selector to indicate no specific language filter is applied"
|
||||
},
|
||||
|
||||
"exerciseSearchMode": "Search mode",
|
||||
"@exerciseSearchMode": {
|
||||
"description": "Heading above the segmented control that lets the user pick between fuzzy and exact name matching"
|
||||
},
|
||||
|
||||
"searchModeFuzzy": "Fuzzy",
|
||||
"@searchModeFuzzy": {
|
||||
"description": "Label for the search mode that performs a fuzzy/substring search on exercise names"
|
||||
},
|
||||
|
||||
"searchModeExact": "Exact",
|
||||
"@searchModeExact": {
|
||||
"description": "Label for the search mode that only matches exercises with this exact name"
|
||||
},
|
||||
"syncStatusConnected": "Connected",
|
||||
"@syncStatusConnected": {
|
||||
"description": "Tooltip on the sync icon when the app is online and idle (no upload or download in progress)"
|
||||
},
|
||||
"syncStatusConnecting": "Connecting",
|
||||
"@syncStatusConnecting": {
|
||||
"description": "Tooltip on the sync icon while the app is establishing a connection to the sync service"
|
||||
},
|
||||
"syncStatusDisconnected": "Not connected",
|
||||
"@syncStatusDisconnected": {
|
||||
"description": "Tooltip on the sync icon when the app has no active connection to the sync service"
|
||||
},
|
||||
"syncStatusUploading": "Uploading",
|
||||
"@syncStatusUploading": {
|
||||
"description": "Tooltip on the sync icon while local changes are being uploaded to the server"
|
||||
},
|
||||
"syncStatusDownloading": "Downloading",
|
||||
"@syncStatusDownloading": {
|
||||
"description": "Tooltip on the sync icon while remote changes are being downloaded from the server"
|
||||
},
|
||||
"syncStatusSyncing": "Synchronizing",
|
||||
"@syncStatusSyncing": {
|
||||
"description": "Tooltip on the sync icon when the app is uploading and downloading at the same time"
|
||||
},
|
||||
"syncStatusError": "Sync error",
|
||||
"@syncStatusError": {
|
||||
"description": "Status label shown in the sync status dialog when the latest sync attempt failed"
|
||||
},
|
||||
"syncStatusDialogTitle": "Sync status",
|
||||
"@syncStatusDialogTitle": {
|
||||
"description": "Title of the dialog opened by tapping the sync icon in the app bar"
|
||||
},
|
||||
"syncStatusLastSynced": "Last synchronisation",
|
||||
"@syncStatusLastSynced": {
|
||||
"description": "Label in the sync status dialog above the timestamp of the last successful sync"
|
||||
},
|
||||
"syncStatusErrorDetails": "Error details",
|
||||
"@syncStatusErrorDetails": {
|
||||
"description": "Header of the expandable section in the sync status dialog that reveals the raw error message"
|
||||
},
|
||||
"filterNutriscore": "Nutri-Score filter",
|
||||
"@filterNutriscore": {
|
||||
"description": "Heading for the Nutri-Score slider in the ingredient search filter dialog"
|
||||
@@ -1270,5 +1381,17 @@
|
||||
"viewDocumentation": "View documentation",
|
||||
"@viewDocumentation": {
|
||||
"description": "Button label to open the documentation about server configuration"
|
||||
}
|
||||
},
|
||||
"sessionExpired": "Your session has expired, please log in again",
|
||||
"@sessionExpired": {
|
||||
"description": "Snackbar message shown when the saved login token is no longer valid"
|
||||
},
|
||||
"weightOrRepsRequired": "Please enter a weight, repetitions, or both",
|
||||
"@weightOrRepsRequired": {
|
||||
"description": "Validation error when both weight and repetitions are empty in a workout log"
|
||||
},
|
||||
"timeStartEndBothOrNeither": "Either set both start and end time or leave both empty",
|
||||
"@timeStartEndBothOrNeither": {
|
||||
"description": "Validation error when only one of start/end time is set on a workout session"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -725,7 +725,6 @@
|
||||
"errorInfoDescription2": "Puedes seguir utilizando la aplicación pero algunas características pueden no funcionar.",
|
||||
"errorViewDetails": "Detalles técnicos",
|
||||
"errorCouldNotConnectToServer": "No se pudo conectar con el servidor",
|
||||
"errorCouldNotConnectToServerDetails": "La aplicación no se pudo conectar con el servidor. Por favor, comprueba to conexión a internet o la URL del servidor y prueba de nuevo. Si el problema persiste, contacta con el administrador del servidor.",
|
||||
"copyToClipboard": "Copiar al portapapeles",
|
||||
"max": "Máximo",
|
||||
"aboutContributeTitle": "Contribuir",
|
||||
|
||||
@@ -265,8 +265,6 @@
|
||||
"@applicationLogs": {},
|
||||
"errorCouldNotConnectToServer": "اتصال به سرور امکان پذیر نیست",
|
||||
"@errorCouldNotConnectToServer": {},
|
||||
"errorCouldNotConnectToServerDetails": "برنامه نمی تواند به سرور وصل شود. لطفاً اتصال اینترنت یا URL سرور خود را بررسی کرده و دوباره امتحان کنید. اگر مشکل ادامه پیدا کرد، با مدیر سرور تماس بگیرید.",
|
||||
"@errorCouldNotConnectToServerDetails": {},
|
||||
"copyToClipboard": "کپی در کلیپ بورد",
|
||||
"@copyToClipboard": {},
|
||||
"weight": "وزن",
|
||||
|
||||
@@ -813,7 +813,6 @@
|
||||
"isRestDayHelp": "Veuillez noter que toutes les séries et tous les exercices seront supprimés lorsque vous marquerez un jour comme jour de repos.",
|
||||
"needsLogsToAdvance": "Nécessite des journaux pour avancer",
|
||||
"errorCouldNotConnectToServer": "Impossible de se connecter au serveur",
|
||||
"errorCouldNotConnectToServerDetails": "L'application n'a pas pu se connecter au serveur. Veuillez vérifier votre connexion internet ou l'URL du serveur et réessayer. Si le problème persiste, contactez l'administrateur du serveur.",
|
||||
"copyToClipboard": "Copier dans le presse-papiers",
|
||||
"max": "Max",
|
||||
"aboutWhySupportTitle": "Open Source et gratuit ❤️",
|
||||
|
||||
@@ -858,8 +858,6 @@
|
||||
"@toAddMealsToThePlanGoToNutritionalPlanDetails": {
|
||||
"description": "Message shown to guide users to the nutritional plan details page to add meals"
|
||||
},
|
||||
"errorCouldNotConnectToServerDetails": "אין באפשרות היישום להתחבר לשרת. נא לבדוק את החיבור לאינטרנט או לכתובת השרת ולנסות שוב. אם הבעיה ממשיכה להתקיים, נא לפנות למנהל השרת.",
|
||||
"@errorCouldNotConnectToServerDetails": {},
|
||||
"chartAllTimeTitle": "{name} בכל הזמנים",
|
||||
"@chartAllTimeTitle": {
|
||||
"description": "All-time chart of 'name' (e.g. 'weight', 'body fat' etc.)",
|
||||
|
||||
@@ -937,7 +937,6 @@
|
||||
"errorViewDetails": "Tehnički detalji",
|
||||
"applicationLogs": "Dnevnici aplikacije",
|
||||
"errorCouldNotConnectToServer": "Neuspjelo povezivanje sa serverom",
|
||||
"errorCouldNotConnectToServerDetails": "Aplikacija se nije mogla povezati sa serverom. Provjeri internetsku vezu ili URL servera i pokušaj ponovo. Ako problem ne nestane, obrati se administratoru servera.",
|
||||
"copyToClipboard": "Kopiraj u međuspremnik",
|
||||
"endDate": "Datum kraja",
|
||||
"@endDate": {
|
||||
|
||||
@@ -901,7 +901,6 @@
|
||||
"needsLogsToAdvanceHelp": "Pilih opsi ini jika Anda ingin rutinitas berlanjut ke hari berikutnya hanya setelah Anda mencatat latihan pada hari tersebut",
|
||||
"setHasNoExercises": "Set ini belum memiliki latihan apa pun!",
|
||||
"aboutBugsListTitle": "Laporkan masalah atau usulkan fitur",
|
||||
"errorCouldNotConnectToServerDetails": "Aplikasi tidak dapat terhubung ke server. Silakan periksa koneksi internet atau URL server anda, lalu coba lagi. Jika masalah terus berlanjut, hubungi administrator server.",
|
||||
"unVerifiedEmail": "Email belum diverifikasi",
|
||||
"progressionRules": "Latihan ini memiliki aturan peningkatan dan tidak dapat diedit melalui aplikasi mobile. Silakan gunakan aplikasi web untuk mengedit latihan ini.",
|
||||
"setHasProgression": "Set memiliki peningkatan",
|
||||
|
||||
@@ -883,7 +883,6 @@
|
||||
"errorInfoDescription2": "Puoi continuare a utilizzare l'app, ma alcune funzionalità potrebbero non funzionare.",
|
||||
"errorViewDetails": "Dettagli Tecnici",
|
||||
"errorCouldNotConnectToServer": "Impossibile connettersi al server",
|
||||
"errorCouldNotConnectToServerDetails": "L'applicazione non è riuscita a connettersi al server. Controlla la tua connessione Internet o l'URL del server e riprova. Se il problema persiste, contatta l'amministratore del server.",
|
||||
"copyToClipboard": "Copia negli appunti",
|
||||
"aboutTranslationListTitle": "Tradurre l'applicazione",
|
||||
"aboutSourceListTitle": "Visualizza il codice sorgente",
|
||||
|
||||
@@ -657,7 +657,6 @@
|
||||
"@toggleDetails": {
|
||||
"description": "Switch to toggle detail / overview"
|
||||
},
|
||||
"errorCouldNotConnectToServerDetails": "애플리케이션이 서버에 연결할 수 없습니다. 인터넷 연결이나 서버 URL을 확인하고 다시 시도해 주세요. 문제가 지속되면 서버 관리자에게 문의하세요.",
|
||||
"max": "최대",
|
||||
"protein": "단백질",
|
||||
"proteinShort": "P",
|
||||
|
||||
@@ -606,7 +606,6 @@
|
||||
"errorViewDetails": "Технички детали",
|
||||
"applicationLogs": "Логови на апликација",
|
||||
"errorCouldNotConnectToServer": "Не може да се поврзе до сервер",
|
||||
"errorCouldNotConnectToServerDetails": "Апликацијата не можеше да се поврзе со серверот. Проверете ја вашата интернет-врска или URL-адресата на серверот и обидете се повторно. Ако проблемот продолжи, контактирајте го администраторот на серверот.",
|
||||
"weight": "Тежина",
|
||||
"@weight": {
|
||||
"description": "The weight of a workout log or body weight entry"
|
||||
|
||||
@@ -351,7 +351,6 @@
|
||||
"errorViewDetails": "Technische details",
|
||||
"applicationLogs": "Applicatie logboek",
|
||||
"errorCouldNotConnectToServer": "Kon niet verbinden met de server",
|
||||
"errorCouldNotConnectToServerDetails": "De applicatie kon geen verbinding maken met de server. Controleer uw internetverbinding of de server-URL en probeer het opnieuw. Als het probleem aanhoudt, neem dan contact op met de serverbeheerder.",
|
||||
"copyToClipboard": "Kopieer naar klembord",
|
||||
"weight": "Gewicht",
|
||||
"@weight": {
|
||||
|
||||
@@ -707,7 +707,6 @@
|
||||
"apiToken": "API Token",
|
||||
"restTime": "Czas odpoczynku",
|
||||
"errorCouldNotConnectToServer": "Nie możemy połączyć się z serwerem",
|
||||
"errorCouldNotConnectToServerDetails": "Aplikacja nie może połączyć się z serwerem. Prosimy sprawdzić swoje połączenie z internetem lub adres URL i spróbować ponownie. Jeżeli problem nadal występuje, skontaktuj się z administratorem.",
|
||||
"aboutWhySupportTitle": "Open Source & za darmo ❤️",
|
||||
"routines": "Rutyny",
|
||||
"newRoutine": "Nowa rutyna",
|
||||
|
||||
@@ -829,7 +829,6 @@
|
||||
"description": "Error message when the user tries to input a API key with forbidden characters"
|
||||
},
|
||||
"errorViewDetails": "Detalhes técnicos",
|
||||
"errorCouldNotConnectToServerDetails": "A aplicação não conseguiu ligar-se ao servidor. Por favor, verifica a ligação à rede ou o URL do servidor e tenta novamente. Se o problema persistir, contacta o administrador do servidor.",
|
||||
"copyToClipboard": "Copia para a memória",
|
||||
"setHasProgressionWarning": "Por favor, nota que, de momento, não é possível editar todos os valores para uma série na aplicação móvel ou configurar a progressão automática. Por agora, por favor, usa a aplicação web.",
|
||||
"startDate": "Data de início",
|
||||
|
||||
@@ -892,7 +892,6 @@
|
||||
"errorInfoDescription2": "Você pode continuar usando o applicativo, mas algumas funcionalidades não estarão disponíveis.",
|
||||
"errorViewDetails": "Detalhes técnicos",
|
||||
"errorCouldNotConnectToServer": "Não foi possível conectar ao servidor",
|
||||
"errorCouldNotConnectToServerDetails": "O aplicativo não conseguiu conectar ao servidor. Verifique sua conexão de internet ou a URL do servidor e tente novamente. Se o problema persistir, contact o administrador.",
|
||||
"copyToClipboard": "Copiar ao clipboard",
|
||||
"min": "Min",
|
||||
"max": "Max",
|
||||
|
||||
@@ -434,7 +434,6 @@
|
||||
},
|
||||
"protein": "Proteína",
|
||||
"resultingRoutine": "Rotina resultante",
|
||||
"errorCouldNotConnectToServerDetails": "A aplicação não conseguiu ligar ao servidor. Verifica a ligação à internet ou o URL do servidor e tenta outra vez. Se continuar, contacta o administrador do servidor.",
|
||||
"needsLogsToAdvanceHelp": "Seleciona se queres que a rotina avance para o próximo dia apenas se registares um treino",
|
||||
"start": "Início",
|
||||
"@start": {
|
||||
|
||||
@@ -415,7 +415,6 @@
|
||||
"errorViewDetails": "Detalii tehnice",
|
||||
"applicationLogs": "Jurnalele aplicației",
|
||||
"errorCouldNotConnectToServer": "Nu ne-am putut conecta la server",
|
||||
"errorCouldNotConnectToServerDetails": "Aplicația nu s-a putut conecta la server. Te rugăm să îți verifici conexiunea la internet sau URL-ul serverului și să încerci din nou. Dacă problema persistă, contactează administratorul serverului.",
|
||||
"copyToClipboard": "Copiază în clipboard",
|
||||
"min": "Min",
|
||||
"max": "Max",
|
||||
|
||||
@@ -811,7 +811,6 @@
|
||||
"needsLogsToAdvanceHelp": "Виберіть, якщо ви бажаєте, щоб програма перейшла до наступного запланованого дня, лише якщо ви зареєстрували тренування на цей день",
|
||||
"setHasProgressionWarning": "Зверніть увагу, що на даний момент неможливо змінити всі параметри набору в мобільному додатку або налаштувати автоматичний прогрес. Наразі використовуйте веб-додаток.",
|
||||
"setHasNoExercises": "У цьому комплексі ще немає вправ!",
|
||||
"errorCouldNotConnectToServerDetails": "Програмі не вдалося підключитися до сервера. Перевірте підключення до Інтернету або URL-адресу сервера та спробуйте ще раз. Якщо проблема не зникає, зверніться до адміністратора сервера.",
|
||||
"errorViewDetails": "Технічні деталі",
|
||||
"errorCouldNotConnectToServer": "Не вдалося підключитися до сервера",
|
||||
"errorInfoDescription2": "Ви можете продовжувати користуватися додатком, але деякі функції можуть не працювати.",
|
||||
|
||||
@@ -896,7 +896,6 @@
|
||||
"errorInfoDescription2": "您可以继续使用这款应用,但部分功能可能无法正常运行。",
|
||||
"errorViewDetails": "错误技术详情",
|
||||
"errorCouldNotConnectToServer": "无法连接到服务器",
|
||||
"errorCouldNotConnectToServerDetails": "应用程序无法连接到服务器。请检查您的网络连接或服务器网址,然后重试。如果问题持续存在,请联系服务器管理员。",
|
||||
"copyToClipboard": "复制",
|
||||
"aboutWhySupportTitle": "开源 & 免费使用",
|
||||
"aboutContributeTitle": "贡献",
|
||||
|
||||
@@ -835,7 +835,6 @@
|
||||
"noIngredientsDefined": "尚未定義食材",
|
||||
"ingredientLogged": "食材已紀錄到日記",
|
||||
"selectMealToLog": "選擇要紀錄到日記的餐點",
|
||||
"errorCouldNotConnectToServerDetails": "無法連線至伺服器。請檢查您的網路連線或伺服器網址,然後再試一次。如果問題仍未解決,請聯絡伺服器管理員。",
|
||||
"copyToClipboard": "複製到剪貼簿",
|
||||
"aboutWhySupportTitle": "開源且免費使用❤️",
|
||||
"barWeight": "槓鈴重量",
|
||||
|
||||
278
lib/main.dart
278
lib/main.dart
@@ -16,28 +16,26 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:extended_image/extended_image.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod;
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wger/core/locator.dart';
|
||||
import 'package:wger/core/error_dialogs.dart';
|
||||
import 'package:wger/core/keys.dart';
|
||||
import 'package:wger/helpers/errors.dart';
|
||||
import 'package:wger/helpers/locale.dart';
|
||||
import 'package:wger/helpers/shared_preferences.dart';
|
||||
import 'package:wger/l10n/generated/app_localizations.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/routines.dart';
|
||||
import 'package:wger/providers/user.dart';
|
||||
import 'package:wger/providers/wger_base_riverpod.dart';
|
||||
import 'package:wger/providers/app_link_router.dart';
|
||||
import 'package:wger/providers/app_settings_notifier.dart';
|
||||
import 'package:wger/providers/auth_notifier.dart';
|
||||
import 'package:wger/providers/auth_state.dart';
|
||||
import 'package:wger/screens/add_exercise_screen.dart';
|
||||
import 'package:wger/screens/auth_screen.dart';
|
||||
import 'package:wger/screens/auto_login_error_screen.dart';
|
||||
import 'package:wger/screens/dashboard.dart';
|
||||
import 'package:wger/screens/exercise_screen.dart';
|
||||
import 'package:wger/screens/exercises_screen.dart';
|
||||
@@ -45,6 +43,8 @@ import 'package:wger/screens/form_screen.dart';
|
||||
import 'package:wger/screens/gallery_screen.dart';
|
||||
import 'package:wger/screens/gym_mode.dart';
|
||||
import 'package:wger/screens/home_tabs_screen.dart';
|
||||
import 'package:wger/screens/ingredient_detail_screen.dart';
|
||||
import 'package:wger/screens/ingredients_screen.dart';
|
||||
import 'package:wger/screens/log_meal_screen.dart';
|
||||
import 'package:wger/screens/log_meals_screen.dart';
|
||||
import 'package:wger/screens/measurement_categories_screen.dart';
|
||||
@@ -52,6 +52,7 @@ import 'package:wger/screens/measurement_entries_screen.dart';
|
||||
import 'package:wger/screens/nutritional_diary_screen.dart';
|
||||
import 'package:wger/screens/nutritional_plan_screen.dart';
|
||||
import 'package:wger/screens/nutritional_plans_screen.dart';
|
||||
import 'package:wger/screens/powersync_unreachable_screen.dart';
|
||||
import 'package:wger/screens/routine_edit_screen.dart';
|
||||
import 'package:wger/screens/routine_list_screen.dart';
|
||||
import 'package:wger/screens/routine_logs_screen.dart';
|
||||
@@ -69,20 +70,32 @@ import 'package:wger/widgets/core/log_overview.dart';
|
||||
import 'package:wger/widgets/core/settings.dart';
|
||||
|
||||
import 'helpers/logs.dart';
|
||||
import 'providers/auth.dart';
|
||||
|
||||
void _setupLogging() {
|
||||
Logger.root.level = kDebugMode ? Level.ALL : Level.INFO;
|
||||
Logger.root.onRecord.listen((record) {
|
||||
// ignore: avoid_print
|
||||
print('${record.level.name}: ${record.time} [${record.loggerName}] ${record.message}');
|
||||
|
||||
// Network errors are expected in, and PowerSync logs one on every retry
|
||||
// against an unreachable backend. Skip the error object and stack trace so
|
||||
// they don't flood the console.
|
||||
final isTransientNetwork = record.error != null && isNetworkError(record.error!);
|
||||
|
||||
// The Logger API has dedicated error / stackTrace fields that can be populated
|
||||
if (record.error != null && !isTransientNetwork) {
|
||||
// ignore: avoid_print
|
||||
print(' error: ${record.error}');
|
||||
}
|
||||
if (record.stackTrace != null && !isTransientNetwork) {
|
||||
// ignore: avoid_print
|
||||
print(record.stackTrace);
|
||||
}
|
||||
|
||||
InMemoryLogStore().add(record);
|
||||
});
|
||||
}
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
|
||||
final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
|
||||
|
||||
void main() async {
|
||||
// Needs to be called before runApp
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
@@ -92,9 +105,6 @@ void main() async {
|
||||
|
||||
final logger = Logger('main');
|
||||
|
||||
// Locator to initialize exerciseDB
|
||||
await ServiceLocator().configure();
|
||||
|
||||
// SharedPreferences to SharedPreferencesAsync migration function
|
||||
await PreferenceHelper.instance.migrationSupportFunctionForSharedPreferences();
|
||||
|
||||
@@ -125,157 +135,107 @@ void main() async {
|
||||
return true;
|
||||
};
|
||||
|
||||
// Sweep image-cache entries older than ~3 months. Fire-and-forget so we
|
||||
// don't delay startup; failures are non-fatal. extended_image otherwise
|
||||
// never evicts on its own, without this the cache only shrinks under
|
||||
// OS storage pressure or via manual clearing in Settings.
|
||||
unawaited(
|
||||
clearDiskCachedImages(duration: const Duration(days: 90))
|
||||
.then((_) => logger.fine('Image cache sweep done'))
|
||||
.catchError((Object e) => logger.warning('Image cache sweep failed: $e')),
|
||||
);
|
||||
|
||||
// Application
|
||||
runApp(const MainApp());
|
||||
runApp(const ProviderScope(child: MainApp()));
|
||||
}
|
||||
|
||||
class MainApp extends StatelessWidget {
|
||||
class MainApp extends ConsumerWidget {
|
||||
const MainApp();
|
||||
|
||||
Widget _getHomeScreen(AuthProvider auth) {
|
||||
switch (auth.state) {
|
||||
case AuthState.loggedIn:
|
||||
return HomeTabsScreen();
|
||||
case AuthState.updateRequired:
|
||||
Widget _getHomeScreen(AuthState auth) {
|
||||
switch (auth.status) {
|
||||
case AuthStatus.loggedIn:
|
||||
return const HomeTabsScreen();
|
||||
case AuthStatus.appUpdateRequired:
|
||||
return const UpdateAppScreen();
|
||||
case AuthState.serverUpdateRequired:
|
||||
case AuthStatus.serverUpdateRequired:
|
||||
return const UpdateServerScreen();
|
||||
default:
|
||||
return FutureBuilder(
|
||||
future: auth.tryAutoLogin(),
|
||||
builder: (ctx, authResultSnapshot) =>
|
||||
authResultSnapshot.connectionState == ConnectionState.waiting
|
||||
? const SplashScreen()
|
||||
: const AuthScreen(),
|
||||
);
|
||||
case AuthStatus.powerSyncUnreachable:
|
||||
return const PowerSyncUnreachableScreen();
|
||||
case AuthStatus.loggedOut:
|
||||
return const AuthScreen();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (ctx) => AuthProvider()),
|
||||
ChangeNotifierProxyProvider<AuthProvider, ExercisesProvider>(
|
||||
create: (context) => ExercisesProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
),
|
||||
update: (context, base, previous) =>
|
||||
previous ?? ExercisesProvider(WgerBaseProvider(base)),
|
||||
),
|
||||
ChangeNotifierProxyProvider2<AuthProvider, ExercisesProvider, RoutinesProvider>(
|
||||
create: (context) => RoutinesProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
Provider.of(context, listen: false),
|
||||
[],
|
||||
),
|
||||
update: (context, auth, exercises, previous) =>
|
||||
previous ?? RoutinesProvider(WgerBaseProvider(auth), exercises, []),
|
||||
),
|
||||
ChangeNotifierProxyProvider<AuthProvider, NutritionPlansProvider>(
|
||||
create: (context) => NutritionPlansProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
[],
|
||||
),
|
||||
update: (context, auth, previous) =>
|
||||
previous ?? NutritionPlansProvider(WgerBaseProvider(auth), []),
|
||||
),
|
||||
ChangeNotifierProxyProvider<AuthProvider, MeasurementProvider>(
|
||||
create: (context) => MeasurementProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
),
|
||||
update: (context, base, previous) =>
|
||||
previous ?? MeasurementProvider(WgerBaseProvider(base)),
|
||||
),
|
||||
ChangeNotifierProxyProvider<AuthProvider, UserProvider>(
|
||||
create: (context) => UserProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
),
|
||||
update: (context, base, previous) => previous ?? UserProvider(WgerBaseProvider(base)),
|
||||
),
|
||||
ChangeNotifierProxyProvider<AuthProvider, BodyWeightProvider>(
|
||||
create: (context) => BodyWeightProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
),
|
||||
update: (context, base, previous) =>
|
||||
previous ?? BodyWeightProvider(WgerBaseProvider(base)),
|
||||
),
|
||||
ChangeNotifierProxyProvider<AuthProvider, GalleryProvider>(
|
||||
create: (context) => GalleryProvider(
|
||||
Provider.of(context, listen: false),
|
||||
[],
|
||||
),
|
||||
update: (context, auth, previous) => previous ?? GalleryProvider(auth, []),
|
||||
),
|
||||
ChangeNotifierProxyProvider<AuthProvider, AddExerciseProvider>(
|
||||
create: (context) => AddExerciseProvider(
|
||||
WgerBaseProvider(Provider.of(context, listen: false)),
|
||||
),
|
||||
update: (context, base, previous) =>
|
||||
previous ?? AddExerciseProvider(WgerBaseProvider(base)),
|
||||
),
|
||||
],
|
||||
child: Consumer<AuthProvider>(
|
||||
builder: (ctx, auth, _) {
|
||||
final baseInstance = WgerBaseProvider(Provider.of(ctx, listen: false));
|
||||
return Consumer<UserProvider>(
|
||||
builder: (ctx, user, _) => riverpod.ProviderScope(
|
||||
overrides: [
|
||||
wgerBaseProvider.overrideWithValue(baseInstance),
|
||||
],
|
||||
child: riverpod.Consumer(
|
||||
builder: (rpCtx, ref, _) {
|
||||
return MaterialApp(
|
||||
title: 'wger',
|
||||
navigatorKey: navigatorKey,
|
||||
scaffoldMessengerKey: scaffoldMessengerKey,
|
||||
theme: wgerLightTheme,
|
||||
darkTheme: wgerDarkTheme,
|
||||
highContrastTheme: wgerLightThemeHc,
|
||||
highContrastDarkTheme: wgerDarkThemeHc,
|
||||
themeMode: user.themeMode,
|
||||
locale: user.userLocale,
|
||||
home: _getHomeScreen(auth),
|
||||
routes: {
|
||||
DashboardScreen.routeName: (ctx) => const DashboardScreen(),
|
||||
FormScreen.routeName: (ctx) => const FormScreen(),
|
||||
GalleryScreen.routeName: (ctx) => const GalleryScreen(),
|
||||
GymModeScreen.routeName: (ctx) => const GymModeScreen(),
|
||||
HomeTabsScreen.routeName: (ctx) => HomeTabsScreen(),
|
||||
MeasurementCategoriesScreen.routeName: (ctx) =>
|
||||
const MeasurementCategoriesScreen(),
|
||||
MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(),
|
||||
NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(),
|
||||
NutritionalDiaryScreen.routeName: (ctx) => const NutritionalDiaryScreen(),
|
||||
NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(),
|
||||
LogMealsScreen.routeName: (ctx) => const LogMealsScreen(),
|
||||
LogMealScreen.routeName: (ctx) => const LogMealScreen(),
|
||||
WeightScreen.routeName: (ctx) => const WeightScreen(),
|
||||
RoutineScreen.routeName: (ctx) => const RoutineScreen(),
|
||||
RoutineEditScreen.routeName: (ctx) => const RoutineEditScreen(),
|
||||
WorkoutLogsScreen.routeName: (ctx) => const WorkoutLogsScreen(),
|
||||
RoutineListScreen.routeName: (ctx) => const RoutineListScreen(),
|
||||
ExercisesScreen.routeName: (ctx) => const ExercisesScreen(),
|
||||
ExerciseDetailScreen.routeName: (ctx) => const ExerciseDetailScreen(),
|
||||
AddExerciseScreen.routeName: (ctx) => const AddExerciseScreen(),
|
||||
AboutPage.routeName: (ctx) => const AboutPage(),
|
||||
SettingsPage.routeName: (ctx) => const SettingsPage(),
|
||||
LogOverviewPage.routeName: (ctx) => const LogOverviewPage(),
|
||||
ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(),
|
||||
ConfigureDashboardWidgetsScreen.routeName: (ctx) =>
|
||||
const ConfigureDashboardWidgetsScreen(),
|
||||
TrophyScreen.routeName: (ctx) => const TrophyScreen(),
|
||||
},
|
||||
localeListResolutionCallback: resolveLocale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final authAsync = ref.watch(authProvider);
|
||||
// Instantiates the singleton on first build; the provider subscribes to
|
||||
// incoming deep links as a side effect of being read.
|
||||
ref.watch(appLinkRouterProvider);
|
||||
|
||||
return authAsync.when(
|
||||
loading: () => const MaterialApp(home: SplashScreen()),
|
||||
error: (error, stack) => MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: AutoLoginErrorScreen(error: error),
|
||||
),
|
||||
data: (authState) {
|
||||
final themeMode = ref.watch(
|
||||
appSettingsProvider.select((s) => s.value?.themeMode ?? ThemeMode.system),
|
||||
);
|
||||
final userLocale = ref.watch(
|
||||
appSettingsProvider.select((s) => s.value?.userLocale),
|
||||
);
|
||||
|
||||
return MaterialApp(
|
||||
title: 'wger',
|
||||
navigatorKey: navigatorKey,
|
||||
scaffoldMessengerKey: scaffoldMessengerKey,
|
||||
theme: wgerLightTheme,
|
||||
darkTheme: wgerDarkTheme,
|
||||
highContrastTheme: wgerLightThemeHc,
|
||||
highContrastDarkTheme: wgerDarkThemeHc,
|
||||
themeMode: themeMode,
|
||||
locale: userLocale,
|
||||
home: _getHomeScreen(authState),
|
||||
routes: {
|
||||
DashboardScreen.routeName: (ctx) => const DashboardScreen(),
|
||||
FormScreen.routeName: (ctx) => const FormScreen(),
|
||||
GalleryScreen.routeName: (ctx) => const GalleryScreen(),
|
||||
GymModeScreen.routeName: (ctx) => const GymModeScreen(),
|
||||
HomeTabsScreen.routeName: (ctx) => const HomeTabsScreen(),
|
||||
MeasurementCategoriesScreen.routeName: (ctx) => const MeasurementCategoriesScreen(),
|
||||
MeasurementEntriesScreen.routeName: (ctx) => const MeasurementEntriesScreen(),
|
||||
NutritionalPlansScreen.routeName: (ctx) => const NutritionalPlansScreen(),
|
||||
NutritionalDiaryScreen.routeName: (ctx) => const NutritionalDiaryScreen(),
|
||||
NutritionalPlanScreen.routeName: (ctx) => const NutritionalPlanScreen(),
|
||||
IngredientDetailScreen.routeName: (ctx) => const IngredientDetailScreen(),
|
||||
IngredientsScreen.routeName: (ctx) => const IngredientsScreen(),
|
||||
LogMealsScreen.routeName: (ctx) => const LogMealsScreen(),
|
||||
LogMealScreen.routeName: (ctx) => const LogMealScreen(),
|
||||
WeightScreen.routeName: (ctx) => const WeightScreen(),
|
||||
RoutineScreen.routeName: (ctx) => const RoutineScreen(),
|
||||
RoutineEditScreen.routeName: (ctx) => const RoutineEditScreen(),
|
||||
WorkoutLogsScreen.routeName: (ctx) => const WorkoutLogsScreen(),
|
||||
RoutineListScreen.routeName: (ctx) => const RoutineListScreen(),
|
||||
ExercisesScreen.routeName: (ctx) => const ExercisesScreen(),
|
||||
ExerciseDetailScreen.routeName: (ctx) => const ExerciseDetailScreen(),
|
||||
AddExerciseScreen.routeName: (ctx) => const AddExerciseScreen(),
|
||||
AboutPage.routeName: (ctx) => const AboutPage(),
|
||||
SettingsPage.routeName: (ctx) => const SettingsPage(),
|
||||
LogOverviewPage.routeName: (ctx) => const LogOverviewPage(),
|
||||
ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(),
|
||||
ConfigureDashboardWidgetsScreen.routeName: (ctx) =>
|
||||
const ConfigureDashboardWidgetsScreen(),
|
||||
TrophyScreen.routeName: (ctx) => const TrophyScreen(),
|
||||
},
|
||||
localeListResolutionCallback: resolveLocale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (C) 2020, 2021 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
|
||||
@@ -16,23 +16,24 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
import 'package:wger/helpers/json.dart';
|
||||
import 'package:drift/drift.dart';
|
||||
import 'package:wger/database/powersync/database.dart';
|
||||
|
||||
part 'weight_entry.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class WeightEntry {
|
||||
@JsonKey(required: true)
|
||||
int? id;
|
||||
static const minValue = 30;
|
||||
static const maxValue = 300;
|
||||
|
||||
static const stepperSmall = 0.1;
|
||||
static const stepperBig = 1;
|
||||
|
||||
/// Client-generated UUID, is `null` only before the first persist
|
||||
String? id;
|
||||
|
||||
@JsonKey(required: true, fromJson: stringToNum, toJson: numToString)
|
||||
late num weight = 0;
|
||||
|
||||
@JsonKey(required: true, fromJson: utcIso8601ToLocalDate, toJson: dateToUtcIso8601)
|
||||
late DateTime date;
|
||||
|
||||
WeightEntry({this.id, weight, DateTime? date}) {
|
||||
WeightEntry({this.id, num? weight, DateTime? date}) {
|
||||
this.date = date ?? DateTime.now();
|
||||
|
||||
if (weight != null) {
|
||||
@@ -40,14 +41,17 @@ class WeightEntry {
|
||||
}
|
||||
}
|
||||
|
||||
WeightEntry copyWith({int? id, int? weight, DateTime? date}) => WeightEntry(
|
||||
WeightEntry copyWith({String? id, int? weight, DateTime? date}) => WeightEntry(
|
||||
id: id,
|
||||
weight: weight ?? this.weight,
|
||||
date: date ?? this.date,
|
||||
);
|
||||
|
||||
// Boilerplate
|
||||
factory WeightEntry.fromJson(Map<String, dynamic> json) => _$WeightEntryFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$WeightEntryToJson(this);
|
||||
WeightEntryTableCompanion toCompanion() {
|
||||
return WeightEntryTableCompanion(
|
||||
id: id != null ? Value(id!) : const Value.absent(),
|
||||
date: Value(date),
|
||||
weight: Value(weight as double),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'weight_entry.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
WeightEntry _$WeightEntryFromJson(Map<String, dynamic> json) {
|
||||
$checkKeys(json, requiredKeys: const ['id', 'weight', 'date']);
|
||||
return WeightEntry(
|
||||
id: (json['id'] as num?)?.toInt(),
|
||||
weight: stringToNum(json['weight'] as String?),
|
||||
date: utcIso8601ToLocalDate(json['date'] as String),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$WeightEntryToJson(WeightEntry instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'weight': numToString(instance.weight),
|
||||
'date': dateToUtcIso8601(instance.date),
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
* This file is part of wger Workout Manager <https://github.com/wger-project>.
|
||||
* Copyright (C) 2020, 2021 wger Team
|
||||
* 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
|
||||
31
lib/models/core/license.dart
Normal file
31
lib/models/core/license.dart
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* 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:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'license.freezed.dart';
|
||||
|
||||
@freezed
|
||||
abstract class License with _$License {
|
||||
const factory License({
|
||||
required int id,
|
||||
required String shortName,
|
||||
required String fullName,
|
||||
required String url,
|
||||
}) = _License;
|
||||
}
|
||||
280
lib/models/core/license.freezed.dart
Normal file
280
lib/models/core/license.freezed.dart
Normal file
@@ -0,0 +1,280 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'license.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// dart format off
|
||||
T _$identity<T>(T value) => value;
|
||||
/// @nodoc
|
||||
mixin _$License {
|
||||
|
||||
int get id; String get shortName; String get fullName; String get url;
|
||||
/// Create a copy of License
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$LicenseCopyWith<License> get copyWith => _$LicenseCopyWithImpl<License>(this as License, _$identity);
|
||||
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is License&&(identical(other.id, id) || other.id == id)&&(identical(other.shortName, shortName) || other.shortName == shortName)&&(identical(other.fullName, fullName) || other.fullName == fullName)&&(identical(other.url, url) || other.url == url));
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,id,shortName,fullName,url);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'License(id: $id, shortName: $shortName, fullName: $fullName, url: $url)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $LicenseCopyWith<$Res> {
|
||||
factory $LicenseCopyWith(License value, $Res Function(License) _then) = _$LicenseCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
int id, String shortName, String fullName, String url
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class _$LicenseCopyWithImpl<$Res>
|
||||
implements $LicenseCopyWith<$Res> {
|
||||
_$LicenseCopyWithImpl(this._self, this._then);
|
||||
|
||||
final License _self;
|
||||
final $Res Function(License) _then;
|
||||
|
||||
/// Create a copy of License
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? shortName = null,Object? fullName = null,Object? url = null,}) {
|
||||
return _then(_self.copyWith(
|
||||
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
|
||||
as int,shortName: null == shortName ? _self.shortName : shortName // ignore: cast_nullable_to_non_nullable
|
||||
as String,fullName: null == fullName ? _self.fullName : fullName // ignore: cast_nullable_to_non_nullable
|
||||
as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Adds pattern-matching-related methods to [License].
|
||||
extension LicensePatterns on License {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _License value)? $default,{required TResult orElse(),}){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _License() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _License value) $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _License():
|
||||
return $default(_that);case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
|
||||
}
|
||||
}
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _License value)? $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _License() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( int id, String shortName, String fullName, String url)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _License() when $default != null:
|
||||
return $default(_that.id,_that.shortName,_that.fullName,_that.url);case _:
|
||||
return orElse();
|
||||
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( int id, String shortName, String fullName, String url) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _License():
|
||||
return $default(_that.id,_that.shortName,_that.fullName,_that.url);case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( int id, String shortName, String fullName, String url)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _License() when $default != null:
|
||||
return $default(_that.id,_that.shortName,_that.fullName,_that.url);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
|
||||
class _License implements License {
|
||||
const _License({required this.id, required this.shortName, required this.fullName, required this.url});
|
||||
|
||||
|
||||
@override final int id;
|
||||
@override final String shortName;
|
||||
@override final String fullName;
|
||||
@override final String url;
|
||||
|
||||
/// Create a copy of License
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$LicenseCopyWith<_License> get copyWith => __$LicenseCopyWithImpl<_License>(this, _$identity);
|
||||
|
||||
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _License&&(identical(other.id, id) || other.id == id)&&(identical(other.shortName, shortName) || other.shortName == shortName)&&(identical(other.fullName, fullName) || other.fullName == fullName)&&(identical(other.url, url) || other.url == url));
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,id,shortName,fullName,url);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'License(id: $id, shortName: $shortName, fullName: $fullName, url: $url)';
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$LicenseCopyWith<$Res> implements $LicenseCopyWith<$Res> {
|
||||
factory _$LicenseCopyWith(_License value, $Res Function(_License) _then) = __$LicenseCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
int id, String shortName, String fullName, String url
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class __$LicenseCopyWithImpl<$Res>
|
||||
implements _$LicenseCopyWith<$Res> {
|
||||
__$LicenseCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _License _self;
|
||||
final $Res Function(_License) _then;
|
||||
|
||||
/// Create a copy of License
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? shortName = null,Object? fullName = null,Object? url = null,}) {
|
||||
return _then(_License(
|
||||
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
|
||||
as int,shortName: null == shortName ? _self.shortName : shortName // ignore: cast_nullable_to_non_nullable
|
||||
as String,fullName: null == fullName ? _self.fullName : fullName // ignore: cast_nullable_to_non_nullable
|
||||
as String,url: null == url ? _self.url : url // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// dart format on
|
||||
@@ -16,25 +16,10 @@
|
||||
* 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(name: 'translation')
|
||||
final int? translationId;
|
||||
|
||||
@JsonKey(required: true)
|
||||
final String alias;
|
||||
|
||||
const Alias({this.id, required this.translationId, required this.alias});
|
||||
|
||||
// Boilerplate
|
||||
factory Alias.fromJson(Map<String, dynamic> json) => _$AliasFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$AliasToJson(this);
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'alias.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Alias _$AliasFromJson(Map<String, dynamic> json) {
|
||||
$checkKeys(json, requiredKeys: const ['id', 'alias']);
|
||||
return Alias(
|
||||
id: (json['id'] as num?)?.toInt(),
|
||||
translationId: (json['translation'] as num?)?.toInt(),
|
||||
alias: json['alias'] as String,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$AliasToJson(Alias instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'translation': instance.translationId,
|
||||
'alias': instance.alias,
|
||||
};
|
||||
@@ -17,16 +17,9 @@
|
||||
*/
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'category.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class ExerciseCategory extends Equatable {
|
||||
@JsonKey(required: true)
|
||||
final int id;
|
||||
|
||||
@JsonKey(required: true)
|
||||
final String name;
|
||||
|
||||
const ExerciseCategory({required this.id, required this.name});
|
||||
@@ -36,10 +29,6 @@ class ExerciseCategory extends Equatable {
|
||||
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];
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'category.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
ExerciseCategory _$ExerciseCategoryFromJson(Map<String, dynamic> json) {
|
||||
$checkKeys(json, requiredKeys: const ['id', 'name']);
|
||||
return ExerciseCategory(
|
||||
id: (json['id'] as num).toInt(),
|
||||
name: json['name'] as String,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$ExerciseCategoryToJson(ExerciseCategory instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
};
|
||||
@@ -16,19 +16,9 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'comment.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class Comment {
|
||||
@JsonKey(required: true)
|
||||
final int id;
|
||||
|
||||
@JsonKey(name: 'translation')
|
||||
final int translationId;
|
||||
|
||||
@JsonKey(required: true)
|
||||
final String comment;
|
||||
|
||||
const Comment({
|
||||
@@ -36,9 +26,4 @@ class Comment {
|
||||
required this.translationId,
|
||||
required this.comment,
|
||||
});
|
||||
|
||||
// Boilerplate
|
||||
factory Comment.fromJson(Map<String, dynamic> json) => _$CommentFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$CommentToJson(this);
|
||||
}
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'comment.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Comment _$CommentFromJson(Map<String, dynamic> json) {
|
||||
$checkKeys(json, requiredKeys: const ['id', 'comment']);
|
||||
return Comment(
|
||||
id: (json['id'] as num).toInt(),
|
||||
translationId: (json['translation'] as num).toInt(),
|
||||
comment: json['comment'] as String,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$CommentToJson(Comment instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'translation': instance.translationId,
|
||||
'comment': instance.comment,
|
||||
};
|
||||
@@ -17,24 +17,13 @@
|
||||
*/
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'equipment.g.dart';
|
||||
|
||||
@JsonSerializable()
|
||||
class Equipment extends Equatable {
|
||||
@JsonKey(required: true)
|
||||
final int id;
|
||||
|
||||
@JsonKey(required: true)
|
||||
final String name;
|
||||
|
||||
const Equipment({required this.id, required this.name});
|
||||
|
||||
// Boilerplate
|
||||
factory Equipment.fromJson(Map<String, dynamic> json) => _$EquipmentFromJson(json);
|
||||
Map<String, dynamic> toJson() => _$EquipmentToJson(this);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, name];
|
||||
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'equipment.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
Equipment _$EquipmentFromJson(Map<String, dynamic> json) {
|
||||
$checkKeys(json, requiredKeys: const ['id', 'name']);
|
||||
return Equipment(
|
||||
id: (json['id'] as num).toInt(),
|
||||
name: json['name'] as String,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$EquipmentToJson(Equipment instance) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user