fluffychat/lib/pangea/analytics_practice/analytics_practice_page.dart
ggurdin e8428783e6
Fluffychat merge 2 (#5590)
* build: Reenable shrink resources and minify in gradle

* build: (deps): bump image from 4.6.0 to 4.7.1

Bumps [image](https://github.com/brendan-duncan/image) from 4.6.0 to 4.7.1.
- [Changelog](https://github.com/brendan-duncan/image/blob/main/CHANGELOG.md)
- [Commits](https://github.com/brendan-duncan/image/commits)

---
updated-dependencies:
- dependency-name: image
  dependency-version: 4.7.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* build: (deps): bump file_picker from 10.3.7 to 10.3.8

Bumps [file_picker](https://github.com/miguelpruivo/flutter_file_picker) from 10.3.7 to 10.3.8.
- [Release notes](https://github.com/miguelpruivo/flutter_file_picker/releases)
- [Changelog](https://github.com/miguelpruivo/flutter_file_picker/blob/master/CHANGELOG.md)
- [Commits](https://github.com/miguelpruivo/flutter_file_picker/compare/v10.3.7...v10.3.8)

---
updated-dependencies:
- dependency-name: file_picker
  dependency-version: 10.3.8
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

* feat: Improved search

* build: Use matrix sdk vom pub.dev again

* chore: Follow up better search

* build: (deps): bump image from 4.7.1 to 4.7.2

Bumps [image](https://github.com/brendan-duncan/image) from 4.7.1 to 4.7.2.
- [Changelog](https://github.com/brendan-duncan/image/blob/main/CHANGELOG.md)
- [Commits](https://github.com/brendan-duncan/image/commits)

---
updated-dependencies:
- dependency-name: image
  dependency-version: 4.7.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore: Make cross signing self sign mandatory for bootstrap

* chore: Update user device keys before creating bootstrap

* fix: Better wait for secrets after verification bootstrap

* refactor: Remove native imaging and enable web worker

* refactor: Remove unused html onfocus streams

* build: (deps): bump flutter_foreground_task from 9.1.0 to 9.2.0

Bumps [flutter_foreground_task](https://github.com/Dev-hwang/flutter_foreground_task) from 9.1.0 to 9.2.0.
- [Changelog](https://github.com/Dev-hwang/flutter_foreground_task/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Dev-hwang/flutter_foreground_task/commits)

---
updated-dependencies:
- dependency-name: flutter_foreground_task
  dependency-version: 9.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(translations): Translated using Weblate (Uzbek)

Currently translated at 99.7% (823 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/uz/

* chore(translations): Translated using Weblate (Russian)

Currently translated at 99.8% (824 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/ru/

* chore(translations): Translated using Weblate (Norwegian Bokmål)

Currently translated at 90.9% (750 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/nb_NO/

* chore(translations): Translated using Weblate (Galician)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/gl/

* chore(translations): Translated using Weblate (Basque)

Currently translated at 99.7% (823 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/eu/

* chore(translations): Translated using Weblate (Ukrainian)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/uk/

* chore(translations): Translated using Weblate (Estonian)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/et/

* chore(translations): Translated using Weblate (Dutch)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/nl/

* chore(translations): Translated using Weblate (Russian)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/ru/

* chore(translations): Translated using Weblate (Spanish)

Currently translated at 95.2% (788 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/es/

* chore(translations): Translated using Weblate (Spanish)

Currently translated at 96.3% (797 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/es/

* chore(translations): Translated using Weblate (Russian)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/ru/

* chore(translations): Translated using Weblate (Russian)

Currently translated at 100.0% (825 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/ru/

* fix: Broken ruzzian plurals

* chore(translations): Translated using Weblate (Norwegian Bokmål)

Currently translated at 91.2% (753 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/nb_NO/

* chore(translations): Translated using Weblate (Bengali)

Currently translated at 4.5% (38 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/bn/

* chore(translations): Translated using Weblate (French)

Currently translated at 82.3% (679 of 825 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/fr/

* build: (deps): bump translations_cleaner from 0.0.5 to 0.1.0

Bumps [translations_cleaner](https://github.com/Chinmay-KB/translations_cleaner) from 0.0.5 to 0.1.0.
- [Changelog](https://github.com/Chinmay-KB/translations_cleaner/blob/main/CHANGELOG.md)
- [Commits](https://github.com/Chinmay-KB/translations_cleaner/commits)

---
updated-dependencies:
- dependency-name: translations_cleaner
  dependency-version: 0.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(translations): Translated using Weblate (German)

Currently translated at 99.2% (821 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/de/

* chore(translations): Translated using Weblate (Estonian)

Currently translated at 100.0% (827 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/et/

* build: Bump version to 2.4.0

* build: (deps): bump sqflite_common_ffi from 2.3.6 to 2.3.7+1

Bumps [sqflite_common_ffi](https://github.com/tekartik/sqflite) from 2.3.6 to 2.3.7+1.
- [Commits](https://github.com/tekartik/sqflite/compare/sqflite_common_ffi_v2.3.6...sqflite_common_ffi/v2.3.7)

---
updated-dependencies:
- dependency-name: sqflite_common_ffi
  dependency-version: 2.3.7+1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

* chore(translations): Translated using Weblate (Czech)

Currently translated at 66.1% (547 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/cs/

* chore(translations): Translated using Weblate (Czech)

Currently translated at 72.7% (602 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/cs/

* chore(translations): Translated using Weblate (German)

Currently translated at 99.8% (826 of 827 strings)

Translation: FluffyChat/Translations
Translate-URL: https://hosted.weblate.org/projects/fluffychat/translations/de/

* chore: Add security.md file

* fix: Locale unlocalized strings

* build: (deps): bump matrix from 4.1.0 to 5.0.0

Bumps [matrix](https://github.com/famedly/matrix-dart-sdk) from 4.1.0 to 5.0.0.
- [Release notes](https://github.com/famedly/matrix-dart-sdk/releases)
- [Changelog](https://github.com/famedly/matrix-dart-sdk/blob/main/CHANGELOG.md)
- [Commits](https://github.com/famedly/matrix-dart-sdk/compare/v4.1.0...v5.0.0)

---
updated-dependencies:
- dependency-name: matrix
  dependency-version: 5.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* fix: Notifications on web correctly managed when tab not focused

* chore: Add changelog for android

* chore: Remove duplicated localization

* fix: Sign in label

* chore: Versionize fcm shared isolate

* build: Remove unused packag

* build: (deps): bump package_info_plus from 8.3.1 to 9.0.0

Bumps [package_info_plus](https://github.com/fluttercommunity/plus_plugins/tree/main/packages/package_info_plus) from 8.3.1 to 9.0.0.
- [Release notes](https://github.com/fluttercommunity/plus_plugins/releases)
- [Commits](https://github.com/fluttercommunity/plus_plugins/commits/package_info_plus-v9.0.0/packages/package_info_plus)

---
updated-dependencies:
- dependency-name: package_info_plus
  dependency-version: 9.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* feat: Display particle animation on login page

* chore: Use fixed version of fcm shared isolate

* fix: apk crash on some platforms due new flutter version

* chore: Correct kotlin format

* fix iOS notifications

* fluffychat merge

* fluffychat merge

* fluffychat merge

* fluffychat merge

* fluffychat merge

* fluffychat merge

* add missing type annotations

* update matrix version

* fluffychat merge

* fluffychat merge

* fix notification on click actions

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Christian Kußowski <c.kussowski@famedly.com>
Co-authored-by: Krille-chan <christian-kussowski@posteo.de>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: BeMeritus <bemerituss@gmail.com>
Co-authored-by: Frank Paul Silye <frankps@gmail.com>
Co-authored-by: josé m. <correoxm@disroot.org>
Co-authored-by: xabirequejo <xabi.rn@gmail.com>
Co-authored-by: Ihor Hordiichuk <igor_ck@outlook.com>
Co-authored-by: Priit Jõerüüt <jrthwlate@users.noreply.hosted.weblate.org>
Co-authored-by: Jelv <post@jelv.nl>
Co-authored-by: Дмитрий Михирев <bizdelnick@gmail.com>
Co-authored-by: Kimby <kimbyqs@gmail.com>
Co-authored-by: Christian <christian-pauly@posteo.de>
Co-authored-by: Kom nake <kominak310@svcache.com>
Co-authored-by: hugues de keyzer <komputilisto@hugues.info>
Co-authored-by: nautilusx <translate@disroot.org>
Co-authored-by: Šebestová <ka.sebestova.cz@gmail.com>
2026-02-10 08:01:12 -05:00

702 lines
22 KiB
Dart

import 'dart:async';
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:collection/collection.dart';
import 'package:fluffychat/l10n/l10n.dart';
import 'package:fluffychat/pangea/analytics_data/analytics_data_service.dart';
import 'package:fluffychat/pangea/analytics_data/analytics_updater_mixin.dart';
import 'package:fluffychat/pangea/analytics_data/derived_analytics_data_model.dart';
import 'package:fluffychat/pangea/analytics_misc/construct_type_enum.dart';
import 'package:fluffychat/pangea/analytics_misc/construct_use_type_enum.dart';
import 'package:fluffychat/pangea/analytics_misc/constructs_model.dart';
import 'package:fluffychat/pangea/analytics_misc/example_message_util.dart';
import 'package:fluffychat/pangea/analytics_practice/analytics_practice_constants.dart';
import 'package:fluffychat/pangea/analytics_practice/analytics_practice_session_model.dart';
import 'package:fluffychat/pangea/analytics_practice/analytics_practice_session_repo.dart';
import 'package:fluffychat/pangea/analytics_practice/analytics_practice_view.dart';
import 'package:fluffychat/pangea/common/utils/async_state.dart';
import 'package:fluffychat/pangea/constructs/construct_identifier.dart';
import 'package:fluffychat/pangea/events/event_wrappers/pangea_message_event.dart';
import 'package:fluffychat/pangea/lemmas/lemma_info_repo.dart';
import 'package:fluffychat/pangea/morphs/morph_features_enum.dart';
import 'package:fluffychat/pangea/practice_activities/activity_type_enum.dart';
import 'package:fluffychat/pangea/practice_activities/message_activity_request.dart';
import 'package:fluffychat/pangea/practice_activities/practice_activity_model.dart';
import 'package:fluffychat/pangea/practice_activities/practice_generation_repo.dart';
import 'package:fluffychat/pangea/text_to_speech/tts_controller.dart';
import 'package:fluffychat/pangea/toolbar/message_practice/message_audio_card.dart';
import 'package:fluffychat/pangea/toolbar/message_practice/practice_record_controller.dart';
import 'package:fluffychat/widgets/future_loading_dialog.dart';
import 'package:fluffychat/widgets/matrix.dart';
class SelectedMorphChoice {
final MorphFeaturesEnum feature;
final String tag;
const SelectedMorphChoice({required this.feature, required this.tag});
}
class VocabPracticeChoice {
final String choiceId;
final String choiceText;
final String? choiceEmoji;
const VocabPracticeChoice({
required this.choiceId,
required this.choiceText,
this.choiceEmoji,
});
}
class _PracticeQueueEntry {
final MessageActivityRequest request;
final Completer<MultipleChoicePracticeActivityModel> completer;
_PracticeQueueEntry({required this.request, required this.completer});
}
class SessionLoader extends AsyncLoader<AnalyticsPracticeSessionModel> {
final ConstructTypeEnum type;
SessionLoader({required this.type});
@override
Future<AnalyticsPracticeSessionModel> fetch() =>
AnalyticsPracticeSessionRepo.get(type);
}
class AnalyticsPractice extends StatefulWidget {
static bool bypassExitConfirmation = true;
final ConstructTypeEnum type;
const AnalyticsPractice({super.key, required this.type});
@override
AnalyticsPracticeState createState() => AnalyticsPracticeState();
}
class AnalyticsPracticeState extends State<AnalyticsPractice>
with AnalyticsUpdater {
late final SessionLoader _sessionLoader;
final ValueNotifier<AsyncState<MultipleChoicePracticeActivityModel>>
activityState = ValueNotifier(const AsyncState.idle());
final Queue<_PracticeQueueEntry> _queue = Queue();
final ValueNotifier<MessageActivityRequest?> activityTarget =
ValueNotifier<MessageActivityRequest?>(null);
final ValueNotifier<double> progressNotifier = ValueNotifier<double>(0.0);
final ValueNotifier<bool> enableChoicesNotifier = ValueNotifier<bool>(true);
final ValueNotifier<SelectedMorphChoice?> selectedMorphChoice =
ValueNotifier<SelectedMorphChoice?>(null);
final ValueNotifier<bool> hintPressedNotifier = ValueNotifier<bool>(false);
final Set<String> _selectedCorrectAnswers = {};
// Track if we're showing the completion message for audio activities
final ValueNotifier<bool> showingAudioCompletion = ValueNotifier<bool>(false);
final ValueNotifier<int> hintsUsedNotifier = ValueNotifier<int>(0);
static const int maxHints = 5;
final Map<String, Map<String, String>> _choiceTexts = {};
final Map<String, Map<String, String?>> _choiceEmojis = {};
final Map<String, PangeaAudioFile> _audioFiles = {};
StreamSubscription<void>? _languageStreamSubscription;
@override
void initState() {
super.initState();
_sessionLoader = SessionLoader(type: widget.type);
_startSession();
_languageStreamSubscription = MatrixState
.pangeaController
.userController
.languageStream
.stream
.listen((_) => _onLanguageUpdate());
}
@override
void dispose() {
_languageStreamSubscription?.cancel();
_sessionLoader.dispose();
activityState.dispose();
activityTarget.dispose();
progressNotifier.dispose();
enableChoicesNotifier.dispose();
selectedMorphChoice.dispose();
hintPressedNotifier.dispose();
showingAudioCompletion.dispose();
hintsUsedNotifier.dispose();
super.dispose();
}
MultipleChoicePracticeActivityModel? get _currentActivity =>
activityState.value is AsyncLoaded<MultipleChoicePracticeActivityModel>
? (activityState.value
as AsyncLoaded<MultipleChoicePracticeActivityModel>)
.value
: null;
bool get _isComplete => _sessionLoader.value?.isComplete ?? false;
ValueNotifier<AsyncState<AnalyticsPracticeSessionModel>> get sessionState =>
_sessionLoader.state;
AnalyticsDataService get _analyticsService =>
Matrix.of(context).analyticsDataService;
List<VocabPracticeChoice> filteredChoices(
MultipleChoicePracticeActivityModel activity,
) {
final content = activity.multipleChoiceContent;
final choices = content.choices.toList();
final answer = content.answers.first;
final filtered = <VocabPracticeChoice>[];
final seenTexts = <String>{};
for (final id in choices) {
final text = getChoiceText(activity.storageKey, id);
if (seenTexts.contains(text)) {
if (id != answer) {
continue;
}
final index = filtered.indexWhere(
(choice) => choice.choiceText == text,
);
if (index != -1) {
filtered[index] = VocabPracticeChoice(
choiceId: id,
choiceText: text,
choiceEmoji: getChoiceEmoji(activity.storageKey, id),
);
}
continue;
}
seenTexts.add(text);
filtered.add(
VocabPracticeChoice(
choiceId: id,
choiceText: text,
choiceEmoji: getChoiceEmoji(activity.storageKey, id),
),
);
}
return filtered;
}
String getChoiceText(String key, String choiceId) {
if (widget.type == ConstructTypeEnum.morph) {
return choiceId;
}
if (_choiceTexts.containsKey(key) &&
_choiceTexts[key]!.containsKey(choiceId)) {
return _choiceTexts[key]![choiceId]!;
}
final cId = ConstructIdentifier.fromString(choiceId);
return cId?.lemma ?? choiceId;
}
String? getChoiceEmoji(String key, String choiceId) {
if (widget.type == ConstructTypeEnum.morph) return null;
return _choiceEmojis[key]?[choiceId];
}
String choiceTargetId(String choiceId) =>
'${widget.type.name}-choice-card-${choiceId.replaceAll(' ', '_')}';
void _clearState() {
activityState.value = const AsyncState.loading();
activityTarget.value = null;
selectedMorphChoice.value = null;
hintPressedNotifier.value = false;
hintsUsedNotifier.value = 0;
enableChoicesNotifier.value = true;
progressNotifier.value = 0.0;
showingAudioCompletion.value = false;
_queue.clear();
_choiceTexts.clear();
_choiceEmojis.clear();
activityState.value = const AsyncState.idle();
AnalyticsPractice.bypassExitConfirmation = true;
}
void updateElapsedTime(int seconds) {
if (_sessionLoader.isLoaded) {
_sessionLoader.value!.setElapsedSeconds(seconds);
}
}
void _playAudio() {
if (activityTarget.value == null) return;
if (widget.type == ConstructTypeEnum.vocab &&
_currentActivity is VocabMeaningPracticeActivityModel) {
} else {
return;
}
TtsController.tryToSpeak(
activityTarget.value!.target.tokens.first.vocabConstructID.lemma,
langCode: MatrixState.pangeaController.userController.userL2!.langCode,
);
}
Future<void> _waitForAnalytics() async {
if (!_analyticsService.initCompleter.isCompleted) {
MatrixState.pangeaController.initControllers();
await _analyticsService.initCompleter.future;
}
}
Future<void> _onLanguageUpdate() async {
try {
_clearState();
await _analyticsService
.updateDispatcher
.constructUpdateStream
.stream
.first
.timeout(const Duration(seconds: 10));
await reloadSession();
} catch (e) {
if (mounted) {
activityState.value = AsyncState.error(
L10n.of(context).oopsSomethingWentWrong,
);
}
}
}
Future<void> _startSession() async {
await _waitForAnalytics();
await _sessionLoader.load();
if (_sessionLoader.isError) {
AnalyticsPractice.bypassExitConfirmation = true;
return;
}
progressNotifier.value = _sessionLoader.value!.progress;
await _continueSession();
}
Future<void> reloadSession() async {
_clearState();
_sessionLoader.reset();
await _startSession();
}
Future<void> reloadCurrentActivity() async {
if (activityTarget.value == null) return;
try {
activityState.value = const AsyncState.loading();
selectedMorphChoice.value = null;
hintPressedNotifier.value = false;
final req = activityTarget.value!;
final res = await _fetchActivity(req);
if (!mounted) return;
activityState.value = AsyncState.loaded(res);
_playAudio();
} catch (e) {
if (!mounted) return;
activityState.value = AsyncState.error(e);
}
}
Future<void> _completeSession() async {
_sessionLoader.value!.finishSession();
setState(() {});
final bonus = _sessionLoader.value!.state.allBonusUses;
await _analyticsService.updateService.addAnalytics(
null,
bonus,
forceUpdate: true,
);
AnalyticsPractice.bypassExitConfirmation = true;
}
bool _continuing = false;
Future<void> _continueSession() async {
if (_continuing) return;
_continuing = true;
enableChoicesNotifier.value = true;
showingAudioCompletion.value = false;
try {
if (activityState.value
is AsyncIdle<MultipleChoicePracticeActivityModel>) {
await _initActivityData();
} else {
// Keep trying to load activities from the queue until one succeeds or queue is empty
while (_queue.isNotEmpty) {
activityState.value = const AsyncState.loading();
selectedMorphChoice.value = null;
hintPressedNotifier.value = false;
_selectedCorrectAnswers.clear();
final nextActivityCompleter = _queue.removeFirst();
try {
final activity = await nextActivityCompleter.completer.future;
activityTarget.value = nextActivityCompleter.request;
_playAudio();
activityState.value = AsyncState.loaded(activity);
AnalyticsPractice.bypassExitConfirmation = false;
return;
} catch (e) {
// Completer failed, skip to next
continue;
}
}
// Queue is empty, complete the session
await _completeSession();
}
} catch (e) {
AnalyticsPractice.bypassExitConfirmation = true;
activityState.value = AsyncState.error(e);
} finally {
_continuing = false;
}
}
Future<void> _initActivityData() async {
final requests = _sessionLoader.value!.activityRequests;
if (requests.isEmpty) {
throw L10n.of(context).noActivityRequest;
}
for (var i = 0; i < requests.length; i++) {
try {
activityState.value = const AsyncState.loading();
final req = requests[i];
final res = await _fetchActivity(req);
if (!mounted) return;
activityTarget.value = req;
_playAudio();
activityState.value = AsyncState.loaded(res);
AnalyticsPractice.bypassExitConfirmation = false;
// Fill queue with remaining requests
_fillActivityQueue(requests.skip(i + 1).toList());
return;
} catch (e) {
await recordSkippedUse(requests[i]);
// Try next request
continue;
}
}
AnalyticsPractice.bypassExitConfirmation = true;
if (!mounted) return;
activityState.value = AsyncState.error(
L10n.of(context).oopsSomethingWentWrong,
);
return;
}
Future<void> _fillActivityQueue(List<MessageActivityRequest> requests) async {
for (final request in requests) {
final completer = Completer<MultipleChoicePracticeActivityModel>();
_queue.add(_PracticeQueueEntry(request: request, completer: completer));
try {
final res = await _fetchActivity(request);
if (!mounted) return;
completer.complete(res);
} catch (e) {
if (!mounted) return;
completer.completeError(e);
await recordSkippedUse(request);
}
}
}
Future<MultipleChoicePracticeActivityModel> _fetchActivity(
MessageActivityRequest req,
) async {
final result = await PracticeRepo.getPracticeActivity(req, messageInfo: {});
if (result.isError ||
result.result is! MultipleChoicePracticeActivityModel) {
throw L10n.of(context).oopsSomethingWentWrong;
}
final activityModel = result.result as MultipleChoicePracticeActivityModel;
// Prefetch lemma info for meaning activities before marking ready
if (activityModel is VocabMeaningPracticeActivityModel) {
final choices = activityModel.multipleChoiceContent.choices.toList();
await _fetchLemmaInfo(activityModel.storageKey, choices);
}
// Prefetch audio for audio activities before marking ready
if (activityModel is VocabAudioPracticeActivityModel) {
await _loadAudioForActivity(activityModel);
}
return activityModel;
}
Future<void> _loadAudioForActivity(
VocabAudioPracticeActivityModel activity,
) async {
final eventId = activity.eventId;
final roomId = activity.roomId;
if (eventId == null || roomId == null) {
throw L10n.of(context).oopsSomethingWentWrong;
}
final client = MatrixState.pangeaController.matrixState.client;
final room = client.getRoomById(roomId);
if (room == null) {
throw L10n.of(context).oopsSomethingWentWrong;
}
final event = await room.getEventById(eventId);
if (event == null) {
throw L10n.of(context).oopsSomethingWentWrong;
}
final pangeaEvent = PangeaMessageEvent(
event: event,
timeline: await room.getTimeline(),
ownMessage: event.senderId == client.userID,
);
// Prefetch the audio file
final audioFile = await pangeaEvent.requestTextToSpeech(
activity.langCode,
MatrixState.pangeaController.userController.voice,
);
// Store the audio file with the eventId as key
_audioFiles[eventId] = audioFile;
}
PangeaAudioFile? getAudioFile(String? eventId) {
if (eventId == null) return null;
return _audioFiles[eventId];
}
Future<void> _fetchLemmaInfo(
String requestKey,
List<String> choiceIds,
) async {
final texts = <String, String>{};
final emojis = <String, String?>{};
for (final id in choiceIds) {
final cId = ConstructIdentifier.fromString(id);
if (cId == null) continue;
final res = await cId.getLemmaInfo({});
if (res.isError) {
LemmaInfoRepo.clearCache(cId.lemmaInfoRequest({}));
throw L10n.of(context).oopsSomethingWentWrong;
}
texts[id] = res.result!.meaning;
emojis[id] = res.result!.emoji.firstOrNull;
}
_choiceTexts.putIfAbsent(requestKey, () => {});
_choiceEmojis.putIfAbsent(requestKey, () => {});
_choiceTexts[requestKey]!.addAll(texts);
_choiceEmojis[requestKey]!.addAll(emojis);
}
Future<void> recordSkippedUse(MessageActivityRequest request) async {
// Record a 0 XP use so that activity isn't chosen again soon
_sessionLoader.value!.incrementSkippedActivities();
final token = request.target.tokens.first;
final use = OneConstructUse(
useType: ConstructUseTypeEnum.ignPA,
constructType: widget.type,
metadata: ConstructUseMetaData(roomId: null, timeStamp: DateTime.now()),
category: token.pos,
lemma: token.lemma.text,
form: token.lemma.text,
xp: 0,
);
await _analyticsService.updateService.addAnalytics(null, [use]);
}
void onHintPressed() {
if (hintsUsedNotifier.value >= maxHints) return;
if (!hintPressedNotifier.value) {
hintsUsedNotifier.value++;
}
hintPressedNotifier.value = true;
}
Future<void> onAudioContinuePressed() async {
showingAudioCompletion.value = false;
//Mark this activity as completed, and either load the next or complete the session
_sessionLoader.value!.completeActivity();
progressNotifier.value = _sessionLoader.value!.progress;
if (_queue.isEmpty) {
await _completeSession();
} else if (_isComplete) {
await _completeSession();
} else {
await _continueSession();
}
}
Future<void> onSelectChoice(String choiceContent) async {
if (_currentActivity == null) return;
final activity = _currentActivity!;
// Track the selection for display
if (activity is MorphPracticeActivityModel) {
selectedMorphChoice.value = SelectedMorphChoice(
feature: activity.morphFeature,
tag: choiceContent,
);
}
final isCorrect = activity.multipleChoiceContent.isCorrect(choiceContent);
final isAudioActivity =
activity.activityType == ActivityTypeEnum.lemmaAudio;
if (isAudioActivity && isCorrect) {
_selectedCorrectAnswers.add(choiceContent);
}
if (isCorrect && !isAudioActivity) {
// Non-audio activities disable choices after first correct answer
enableChoicesNotifier.value = false;
}
// Update activity record
PracticeRecordController.onSelectChoice(
choiceContent,
activity.tokens.first,
activity,
);
final use = activity.constructUse(choiceContent);
_sessionLoader.value!.submitAnswer(use);
await _analyticsService.updateService.addAnalytics(
choiceTargetId(choiceContent),
[use],
);
if (!isCorrect) return;
// For audio activities, check if all answers have been selected
if (isAudioActivity) {
final allAnswers = activity.multipleChoiceContent.answers;
final allSelected = allAnswers.every(
(answer) => _selectedCorrectAnswers.contains(answer),
);
if (!allSelected) {
return;
}
// All answers selected, disable choices and show completion message
enableChoicesNotifier.value = false;
await Future.delayed(const Duration(milliseconds: 1000));
showingAudioCompletion.value = true;
return;
}
_playAudio();
// Display the fact that the choice was correct before loading the next activity
await Future.delayed(const Duration(milliseconds: 1000));
// Then mark this activity as completed, and either load the next or complete the session
_sessionLoader.value!.completeActivity();
progressNotifier.value = _sessionLoader.value!.progress;
if (_queue.isEmpty) {
await _completeSession();
} else if (_isComplete) {
await _completeSession();
} else {
await _continueSession();
}
}
Future<List<InlineSpan>?> getExampleMessage(
MessageActivityRequest activityRequest,
) async {
final target = activityRequest.target;
final token = target.tokens.first;
final construct = target.targetTokenConstructID(token);
if (widget.type == ConstructTypeEnum.morph) {
return activityRequest.exampleMessage?.exampleMessage;
}
return ExampleMessageUtil.getExampleMessage(
await _analyticsService.getConstructUse(construct),
Matrix.of(context).client,
);
}
List<InlineSpan>? getAudioExampleMessage() {
final activity = _currentActivity;
if (activity is VocabAudioPracticeActivityModel) {
return activity.exampleMessage.exampleMessage;
}
return null;
}
Future<DerivedAnalyticsDataModel> get derivedAnalyticsData =>
_analyticsService.derivedData;
/// Returns congratulations message based on performance
String getCompletionMessage(BuildContext context) {
final accuracy = _sessionLoader.value?.state.accuracy ?? 0;
final hasTimeBonus =
(_sessionLoader.value?.state.elapsedSeconds ?? 0) <=
AnalyticsPracticeConstants.timeForBonus;
final hintsUsed = hintsUsedNotifier.value;
final bool perfectAccuracy = accuracy == 100;
final bool noHintsUsed = hintsUsed == 0;
final bool hintsAvailable = widget.type == ConstructTypeEnum.morph;
//check how many conditions for bonuses the user met and return message accordingly
final conditionsMet = [
perfectAccuracy,
!hintsAvailable || noHintsUsed,
hasTimeBonus,
].where((c) => c).length;
if (conditionsMet == 3) {
return L10n.of(context).perfectPractice;
}
if (conditionsMet >= 2) {
return L10n.of(context).greatPractice;
}
if (hintsAvailable && noHintsUsed) {
return L10n.of(context).usedNoHints;
}
return L10n.of(context).youveCompletedPractice;
}
@override
Widget build(BuildContext context) => AnalyticsPracticeView(this);
}