-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathfeature_access.dart
More file actions
649 lines (566 loc) · 26.1 KB
/
feature_access.dart
File metadata and controls
649 lines (566 loc) · 26.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import 'dart:io';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:webtrit_phone/environment_config.dart';
import 'package:webtrit_phone/extensions/extensions.dart';
import 'package:webtrit_phone/models/models.dart';
import 'package:webtrit_phone/theme/theme.dart';
import 'package:webtrit_phone/utils/utils.dart';
final Logger _logger = Logger('FeatureAccess');
/// This class encapsulates the logic for configuring and managing various app features,
/// including login, bottom menu, settings, calls, messaging, and terms.
/// It initializes these features based on the provided `AppConfig` and `AppPreferences`.
///
/// Configuration Overview:
///
/// 1. **LoginFeature**: Configures custom login options, including embedded login screens
/// and available login actions. The login configuration is based on the data in `AppConfig`.
///
/// 2. **BottomMenuFeature**: Configures the bottom navigation menu, enabling/disabling specific tabs,
/// setting the initial tab, and caching the active tab preference. The tab configuration is sourced
/// from `AppConfig.mainConfig.bottomMenu`.
///
/// 3. **SettingsFeature**: Configures the app's settings screen by defining sections and items
/// based on the platform and the app configuration. It also handles embedded resources for settings items.
/// - **Embedded Resources**: Each setting item can either have an embedded resource linked via an `embeddedResourceId`
/// or by matching the resource's type. Resources are first searched by ID, and if not found, the class searches
/// by type (e.g., `terms` for privacy policy).
/// - **Resource Assignment Priority**:
/// - **First**, the `embeddedResourceId` within the setting item is checked.
/// - **Second**, if no `embeddedResourceId` is found, the resource is searched based on its type (e.g., `terms`).
/// - **Terms Handling**: If a setting item is related to terms (e.g., privacy policy) and no `embeddedResourceId`
/// is provided, `TermsFeature` is used to assign the appropriate terms resource.
///
/// 4. **CallFeature**: Configures call-related settings, including video call support,
/// and configurations for call transfer and encoding. The call configuration is derived from `AppConfig.callConfig`.
///
/// 5. **MessagingFeature**: Configures messaging features, including SMS and internal chat support, based on the
/// system's capabilities and the app configuration. It determines whether the messaging tab is displayed in the app
/// and enables corresponding messaging features.
///
/// 6. **TermsFeature**: Configures access to privacy policy and terms resources. It retrieves the privacy policy URL
/// from embedded resources and assigns it to the appropriate settings item when needed.
class FeatureAccess extends Equatable {
const FeatureAccess._(
this.embeddedConfig,
this.loginConfig,
this.bottomMenuConfig,
this.settingsConfig,
this.callConfig,
this.messagingConfig,
this.contactsConfig,
this.termsConfig,
this.systemNotificationsConfig,
this.sipPresenceConfig,
this.supportedConfig,
this.coreSupport,
this.overrides,
this.loggingConfig,
);
final EmbeddedConfig embeddedConfig;
final LoginConfig loginConfig;
final BottomMenuConfig bottomMenuConfig;
final SettingsConfig settingsConfig;
final CallConfig callConfig;
final MessagingConfig messagingConfig;
final ContactsConfig contactsConfig;
final TermsConfig termsConfig;
final SystemNotificationsConfig systemNotificationsConfig;
final SipPresenceConfig sipPresenceConfig;
final LoggingConfig loggingConfig;
/// Represents the set of features explicitly supported and configured within the application's static [AppConfig].
/// This includes features like theme mode and video call capabilities as defined in the application's build-time configuration.
final SupportedConfig supportedConfig;
/// Provides information about the underlying platform and system capabilities.
/// This determines if certain features, such as voicemail, SMS, chats, system notifications,
/// and SIP presence, are fundamentally supported by the device's operating system or environment.
final CoreSupport coreSupport;
/// Contains feature flags and configurations retrieved from a remote source,
/// such as Firebase Remote Config. These overrides can dynamically enable or disable
/// features at runtime, potentially modifying or extending the behavior defined
/// by [supportedConfig] and [coreSupport].
final FeatureOverrides overrides;
static FeatureAccess create(
AppConfig appConfig,
List<EmbeddedResource> embeddedResources,
CoreSupport coreSupport,
WebtritSystemInfo? systemInfo,
FeatureOverrides featureOverrides,
) {
try {
// Initialize basic features
final embeddedConfig = EmbeddedMapper.map(embeddedResources);
// Initialize dependent features
// Note: TermsConfig must be initialized before SettingsConfig because Settings might fallback to Terms config.
final termsConfig = TermsMapper.map(embeddedResources);
final loginConfig = LoginMapper.map(appConfig, embeddedConfig.embeddedResources);
final bottomMenuConfig = BottomMenuMapper.map(appConfig, embeddedConfig);
final settingsConfig = SettingsMapper.map(appConfig, embeddedResources, coreSupport, termsConfig);
final callConfig = CallMapper.map(appConfig, featureOverrides);
final messagingConfig = MessagingMapper.map(appConfig, coreSupport);
final contactsConfig = ContactsMapper.map(appConfig);
final systemNotificationsConfig = SystemNotificationsMapper.map(coreSupport, appConfig, featureOverrides);
final sipPresenceConfig = SipPresenceMapper.map(systemInfo, appConfig, featureOverrides);
final loggingConfig = LoggingMapper.map(appConfig, featureOverrides);
final supportedConfig = SupportedMapper.map(appConfig.supported);
return FeatureAccess._(
embeddedConfig,
loginConfig,
bottomMenuConfig,
settingsConfig,
callConfig,
messagingConfig,
contactsConfig,
termsConfig,
systemNotificationsConfig,
sipPresenceConfig,
supportedConfig,
coreSupport,
featureOverrides,
loggingConfig,
);
} catch (e, stackTrace) {
_logger.severe('Failed to initialize FeatureAccess', e, stackTrace);
rethrow;
}
}
@override
List<Object?> get props => [
embeddedConfig,
loginConfig,
bottomMenuConfig,
settingsConfig,
callConfig,
messagingConfig,
contactsConfig,
termsConfig,
systemNotificationsConfig,
sipPresenceConfig,
loggingConfig,
supportedConfig,
coreSupport,
overrides,
];
}
/// Mapper responsible for constructing [LoginConfig] from application configuration.
abstract final class LoginMapper {
/// Maps [AppConfig] and pre-processed [EmbeddedData] to a [LoginConfig].
// TODO(Serdun): Refactor login configuration to separate concerns more cleanly.
// Currently, modeSelectActions control both the launch screen and the buttons on the login_mode_select_screen,
// which leads to unclear and tightly coupled logic.
static LoginConfig map(AppConfig appConfig, List<EmbeddedData> embeddedData) {
final rawButtons = appConfig.loginConfig.modeSelect.actions.where((button) => button.enabled);
final buttons = <LoginModeAction>[];
for (final action in rawButtons) {
final loginFlavor = LoginFlavor.values.byName(action.type);
final loginEmbeddedData = embeddedData.firstWhereOrNull((dto) => dto.id == action.embeddedId);
if (loginEmbeddedData != null && loginFlavor == LoginFlavor.embedded) {
buttons.add(
LoginEmbeddedModeButton(
titleL10n: action.titleL10n,
flavor: loginFlavor,
customLoginFeature: loginEmbeddedData,
),
);
} else if (loginFlavor == LoginFlavor.login) {
buttons.add(LoginDefaultModeAction(titleL10n: action.titleL10n, flavor: loginFlavor));
}
}
return LoginConfig(
titleL10n: appConfig.loginConfig.modeSelect.greetingL10n,
actions: List.unmodifiable(buttons),
launchLoginPage: embeddedData.firstWhereOrNull(
(it) => it.id == appConfig.loginConfig.common.fullScreenLaunchEmbeddedResourceId,
),
);
}
}
/// Mapper responsible for transforming [AppConfig] into [BottomMenuConfig].
abstract final class BottomMenuMapper {
/// Maps [AppConfig] and [EmbeddedConfig] to a [BottomMenuConfig].
static BottomMenuConfig map(AppConfig appConfig, EmbeddedConfig embeddedConfig) {
final bottomMenu = appConfig.mainConfig.bottomMenu;
if (bottomMenu.tabs.isEmpty) {
throw Exception('Bottom menu configuration is missing or empty');
}
final bottomMenuTabs = bottomMenu.tabs
.where((tab) => tab.enabled)
.map((tab) => _createBottomMenuTab(tab, embeddedConfig))
.toList();
if (bottomMenuTabs.isEmpty) {
throw Exception('No enabled tabs found in bottom menu configuration');
}
return BottomMenuConfig(tabs: List.unmodifiable(bottomMenuTabs));
}
static BottomMenuTab _createBottomMenuTab(BottomMenuTabScheme tab, EmbeddedConfig embeddedConfig) {
return tab.when(
favorites: (enabled, initial, titleL10n, icon) => FavoritesBottomMenuTab(
enabled: tab.enabled,
initial: tab.initial,
titleL10n: tab.titleL10n,
icon: tab.icon.toIconData(),
),
recents: (enabled, initial, titleL10n, icon, useCdrs) => RecentsBottomMenuTab(
useCdrs: useCdrs,
enabled: tab.enabled,
initial: tab.initial,
titleL10n: tab.titleL10n,
icon: tab.icon.toIconData(),
),
contacts: (enabled, initial, titleL10n, icon, contactSourceTypes) => ContactsBottomMenuTab(
enabled: tab.enabled,
initial: tab.initial,
titleL10n: tab.titleL10n,
icon: tab.icon.toIconData(),
contactSourceTypes: contactSourceTypes.map((type) => ContactSourceType.values.byName(type)).toList(),
),
keypad: (enabled, initial, titleL10n, icon) => KeypadBottomMenuTab(
enabled: tab.enabled,
initial: tab.initial,
titleL10n: tab.titleL10n,
icon: tab.icon.toIconData(),
),
messaging: (enabled, initial, titleL10n, icon) => MessagingBottomMenuTab(
enabled: tab.enabled,
initial: tab.initial,
titleL10n: tab.titleL10n,
icon: tab.icon.toIconData(),
),
embedded: (enabled, initial, titleL10n, icon, embeddedId) {
final embeddedResource = embeddedConfig.embeddedResources.firstWhereOrNull(
(resource) => resource.id == embeddedId,
);
return EmbeddedBottomMenuTab(
id: embeddedId,
enabled: tab.enabled,
initial: tab.initial,
titleL10n: tab.titleL10n,
icon: tab.icon.toIconData(),
data: embeddedResource,
);
},
);
}
}
/// Mapper responsible for building [SettingsConfig] by filtering items
/// based on platform support and core capabilities.
abstract final class SettingsMapper {
/// Maps configuration, embedded resources, and core support to [SettingsConfig].
static SettingsConfig map(
AppConfig appConfig,
List<EmbeddedResource> embeddedResources,
CoreSupport coreSupport,
TermsConfig termsConfig,
) {
final settingSections = <SettingsSection>[];
bool hasVoicemail = false;
for (final section in appConfig.settingsConfig.sections.where((s) => s.enabled)) {
final items = <SettingItem>[];
for (final item in section.items.where((i) => i.enabled)) {
final flavor = SettingsFlavor.values.byName(item.type);
if (!_isFeatureSupportedByPlatform(flavor)) continue;
if (!_isFeatureSupportedByCore(flavor, coreSupport)) continue;
if (flavor == SettingsFlavor.voicemail) {
hasVoicemail = true;
}
final settingItem = SettingItem(
titleL10n: item.titleL10n,
icon: item.icon.toIconData(),
iconColor: item.iconColor?.toColor(),
data: _getEmbeddedDataResource(embeddedResources, item, flavor, termsConfig),
flavor: flavor,
);
items.add(settingItem);
}
if (items.isNotEmpty) {
settingSections.add(SettingsSection(titleL10n: section.titleL10n, items: items));
}
}
return SettingsConfig(voicemailsEnabled: hasVoicemail, sections: List.unmodifiable(settingSections));
}
// TODO (Serdun): Move platform-specific configuration to a separate config file.
static bool _isFeatureSupportedByPlatform(SettingsFlavor flavor) {
return !(flavor == SettingsFlavor.network && !kIsWeb && !Platform.isAndroid);
}
static bool _isFeatureSupportedByCore(SettingsFlavor flavor, CoreSupport coreSupport) {
return flavor != SettingsFlavor.voicemail || coreSupport.supportsVoicemail;
}
static EmbeddedData? _getEmbeddedDataResource(
List<EmbeddedResource> embeddedResources,
AppConfigSettingsItem item,
SettingsFlavor flavor,
TermsConfig termsConfig,
) {
final resource = embeddedResources.firstWhereOrNull((r) => r.id == item.embeddedResourceId);
if (resource?.uriOrNull == null && flavor == SettingsFlavor.terms) {
return termsConfig.configData;
}
if (resource?.uriOrNull == null) return null;
final reconnectStrategy = resource?.reconnectStrategy != null
? ReconnectStrategy.values.byName(resource!.reconnectStrategy!)
: ReconnectStrategy.softReload;
return EmbeddedData(
id: resource!.id,
uri: resource.uriOrNull!,
reconnectStrategy: reconnectStrategy,
titleL10n: item.titleL10n,
enableConsoleLogCapture: resource.enableConsoleLogCapture,
);
}
}
/// Mapper responsible for constructing [CallCapabilitiesConfig] from application configuration
/// and environment settings.
abstract final class CallMapper {
/// Maps [AppConfig] to [CallCapabilitiesConfig].
static CallConfig map(AppConfig appConfig, FeatureOverrides featureOverrides) {
final rawCallConfig = appConfig.callConfig;
final transferConfig = rawCallConfig.transfer;
final encodingConfig = rawCallConfig.encoding;
final peerConnectionConfig = rawCallConfig.peerConnection;
final defaultPresetOverride = encodingConfig.defaultPresetOverride;
// Determine if the media settings UI should be accessible
final encodingViewEnabled = appConfig.settingsConfig.sections.any(
(section) => section.items.any((item) => item.type == SettingsFlavor.mediaSettings.name && item.enabled),
);
// Apply remote overrides
final isVideoEnabled = featureOverrides.isVideoCallEnabled ?? rawCallConfig.videoEnabled;
return CallConfig(
capabilities: CallCapabilitiesConfig(
isVideoCallEnabled: isVideoEnabled,
isBlindTransferEnabled: transferConfig.enableBlindTransfer,
isAttendedTransferEnabled: transferConfig.enableAttendedTransfer,
),
triggerConfig: const CallTriggerConfig(
smsFallback: SmsFallbackTriggerConfig(
enabled: EnvironmentConfig.CALL_TRIGGER_MECHANISM_SMS,
available: EnvironmentConfig.CALL_TRIGGER_MECHANISM_SMS,
),
),
encoding: EncodingConfig(
bypassConfig: encodingConfig.bypassConfig,
configurationAllowed: encodingViewEnabled,
defaultPresetOverride: DefaultPresetOverride(
audioBitrate: defaultPresetOverride.audioBitrate,
videoBitrate: defaultPresetOverride.videoBitrate,
ptime: defaultPresetOverride.ptime,
maxptime: defaultPresetOverride.maxptime,
opusSamplingRate: defaultPresetOverride.opusSamplingRate,
opusBitrate: defaultPresetOverride.opusBitrate,
opusStereo: defaultPresetOverride.opusStereo,
opusDtx: defaultPresetOverride.opusDtx,
removeExtmaps: defaultPresetOverride.removeExtmaps,
removeStaticAudioRtpMaps: defaultPresetOverride.removeStaticAudioRtpMaps,
remapTE8payloadTo101: defaultPresetOverride.remapTE8payloadTo101,
),
),
peerConnection: PeerConnectionSettings(
negotiationSettings: NegotiationSettings(
includeInactiveVideoInOfferAnswer: peerConnectionConfig.negotiation.includeInactiveVideoInOfferAnswer,
),
),
);
}
}
abstract final class MessagingMapper {
/// Maps configuration and core support to [MessagingConfig].
static MessagingConfig map(AppConfig appConfig, CoreSupport coreSupport) {
final tabEnabled = appConfig.mainConfig.bottomMenu.tabs.any(
(tab) => tab.maybeWhen(messaging: (enabled, _, _, _) => enabled, orElse: () => false),
);
return MessagingConfig(
coreSmsSupport: coreSupport.supportsSms,
coreChatsSupport: coreSupport.supportsChats,
tabEnabled: tabEnabled,
groupChatSupport: appConfig.messaging.chats.groupChatButtonEnabled,
contactInfoVideoCallSupport: appConfig.messaging.chats.contactInfo.showVideoButtonAction,
);
}
}
/// Mapper responsible for identifying and preparing terms and privacy policy resources.
abstract final class TermsMapper {
/// Maps embedded resources to [TermsConfig].
///
/// The [TermsConfig] is responsible for assigning the correct terms resource,
/// either from a provided embedded resource ID or by searching for a resource of type `terms`.
static TermsConfig map(List<EmbeddedResource> embeddedResources) {
// Attempt to find the terms resource from the embedded resources list.
final termsResource = embeddedResources.firstWhereOrNull((resource) => resource.type == EmbeddedResourceType.terms);
// TODO(Serdun): It would be better to add a separate privacy policy feature in AppConfig,
// with a direct link to the embedded resource. Implement logic to check if the feature access
// doesn't have a link, and if not, search the embedded resources by type in the list.
if (termsResource == null) {
throw EmbeddedResourceMissingException(
message: 'Terms resource is missing',
embeddedResourceType: EmbeddedResourceType.terms,
);
}
return TermsConfig(
EmbeddedData(
id: termsResource.id,
uri: termsResource.uriOrNull!,
reconnectStrategy: ReconnectStrategy.softReload,
titleL10n: termsResource.toolbar.titleL10n,
),
);
}
}
abstract final class EmbeddedMapper {
/// Maps a list of [EmbeddedResource] to [EmbeddedConfig].
static EmbeddedConfig map(List<EmbeddedResource> embeddedResources) {
final embeddedDataList = embeddedResources.map((resource) {
// If strategy is not provided, default to hard reload.
final reconnectStrategy = resource.reconnectStrategy != null
? ReconnectStrategy.values.byName(resource.reconnectStrategy!)
: ReconnectStrategy.softReload;
return EmbeddedData(
id: resource.id,
uri: Uri.parse(resource.uri),
reconnectStrategy: reconnectStrategy,
payload: resource.payload.map((it) => EmbeddedPayloadData.values.byName(it)).toList(),
);
}).toList();
return EmbeddedConfig(List.unmodifiable(embeddedDataList));
}
}
/// Mapper responsible for evaluating system notification support based on config and core capabilities.
abstract final class SystemNotificationsMapper {
/// Maps [CoreSupport] and [AppConfig] to [SystemNotificationsConfig].
static SystemNotificationsConfig map(
CoreSupport coreSupport,
AppConfig appConfig,
FeatureOverrides featureOverrides,
) {
final supportedFeature = appConfig.supported.whereType<SupportedSystemNotifications>().firstOrNull;
// TODO: Migrate client configurations first before fully removing this property.
// ignore: deprecated_member_use_from_same_package, deprecated_member_use
final baseEnabled = supportedFeature?.enabled ?? appConfig.mainConfig.systemNotificationsEnabled;
// Apply remote overrides
final isEnabled = featureOverrides.isSystemNotificationsEnabled ?? baseEnabled;
return SystemNotificationsConfig(
systemNotificationsSupport: isEnabled && coreSupport.supportsSystemNotifications,
systemNotificationsPushSupport: isEnabled && coreSupport.supportsSystemPushNotifications,
);
}
}
/// Mapper responsible for evaluating SIP presence support based on config and core capabilities.
abstract final class SipPresenceMapper {
/// Maps [CoreSupport] and [AppConfig] to [SipPresenceConfig].
static SipPresenceConfig map(WebtritSystemInfo? systemInfo, AppConfig appConfig, FeatureOverrides featureOverrides) {
final appSupportsBase = appConfig.supported.whereType<SupportedHybridPresence>().isNotEmpty;
final appSupports = featureOverrides.hybridPresenceSupport ?? appSupportsBase;
final backendSupports = systemInfo?.core.hybridPresenceAware ?? false;
final isSupported = appSupports && backendSupports;
final withBlfViaSip = isSupported && (systemInfo?.adapter?.supportsSipDialogs ?? false);
final withpresenceViaSip = isSupported && (systemInfo?.adapter?.supportsSipPresence ?? false);
return SipPresenceConfig(
hybridPresenceSupport: isSupported,
dialogsViaSipBlfSupport: withBlfViaSip,
presenceViaSipSupport: withpresenceViaSip,
);
}
}
/// Mapper responsible for parsing and preparing [ContactsConfig] from application configuration.
abstract final class ContactsMapper {
static const Set<ContactAction> _defaultAppBarActions = {ContactAction.chat};
static const Set<ContactAction> _defaultEmailActions = {ContactAction.sendEmail};
static final Map<String, ContactAction> _actionByName = ContactAction.values.asNameMap();
/// Maps [AppConfig] to [ContactsConfig].
///
/// It parses the actions defined in the contacts configuration for different UI elements.
/// If the config is null or contains invalid values, it falls back to defined defaults.
static ContactsConfig map(AppConfig appConfig) {
final detailsDto = appConfig.contacts.details;
// Pre-calculate the default "All except chat" for phone tiles.
final defaultPhoneActions = ContactAction.values.where((action) => action != ContactAction.chat).toSet();
return ContactsConfig(
detailsConfig: ContactDetailsConfig(
appBarActions: _parseActions(detailsDto.actions.appBar, fallback: _defaultAppBarActions),
phoneTileActions: _parseActions(detailsDto.actions.phoneTile, fallback: defaultPhoneActions),
emailTileActions: _parseActions(detailsDto.actions.emailTile, fallback: _defaultEmailActions),
),
);
}
/// Parses a list of raw action strings into a set of [ContactAction] enums.
static Set<ContactAction> _parseActions(List<String>? rawActions, {required Set<ContactAction> fallback}) {
if (rawActions == null) return fallback;
final parsed = rawActions.map((e) => _actionByName[e]).whereType<ContactAction>().toSet();
return parsed.isEmpty ? fallback : parsed;
}
}
/// Mapper responsible for constructing [SupportedConfig] from the raw list of [SupportedFeature].
///
/// This mapper parses the polymorphic list of features and maps them into a structured
/// configuration object. It handles the resolution logic for each feature:
///
/// 1. **Theme Resolution**: Searches for [SupportedThemeMode]. If missing,
/// it defaults to [ThemeModeConfig.system] (Standard Behavior).
///
/// 2. **Video Call Resolution**: Searches for [SupportedVideoCall]. If missing,
/// it defaults to `false` (disabled), adhering to a "whitelist" approach where
/// features must be explicitly enabled.
abstract final class SupportedMapper {
/// Maps a list of [SupportedFeature]s to a [SupportedConfig].
static SupportedConfig map(List<SupportedFeature> supportedFeatures) {
final themeFeature =
supportedFeatures.firstWhere((e) => e is SupportedThemeMode, orElse: () => const SupportedFeature.themeMode())
as SupportedThemeMode;
final videoCallFeature =
supportedFeatures.firstWhere(
(e) => e is SupportedVideoCall,
orElse: () => const SupportedFeature.videoCall(enabled: false),
)
as SupportedVideoCall;
final configThemeMode = switch (themeFeature.mode) {
ThemeModeConfig.system => ThemeMode.system,
ThemeModeConfig.light => ThemeMode.light,
ThemeModeConfig.dark => ThemeMode.dark,
};
return SupportedConfig(themeMode: configThemeMode, isVideoCallEnabled: videoCallFeature.enabled);
}
}
abstract final class LoggingMapper {
static const _defaultInterval = Duration(seconds: 15);
static const _defaultLogLevel = Level.INFO;
static const _defaultRemoteLoggingEnabled = false;
static LoggingConfig map(AppConfig appConfig, FeatureOverrides overrides) {
final loggingFeature =
appConfig.supported.firstWhereOrNull((e) => e is SupportedLoggingConfig) as SupportedLoggingConfig?;
final logLevel =
overrides.logLevel ??
(loggingFeature != null
? Level.LEVELS.where((l) => l.name == loggingFeature.logLevel).firstOrNull ?? _defaultLogLevel
: _defaultLogLevel);
final monitorCheckInterval =
overrides.monitorCheckInterval ??
(loggingFeature != null ? Duration(seconds: loggingFeature.checkIntervalSec) : _defaultInterval);
return LoggingConfig(
logLevel: logLevel,
monitorCheckInterval: monitorCheckInterval,
remoteLoggingEnabled: overrides.remoteLoggingEnabled ?? _defaultRemoteLoggingEnabled,
);
}
static LoggingConfig mapFromOverridesOnly(FeatureOverrides overrides) {
return LoggingConfig(
logLevel: overrides.logLevel ?? _defaultLogLevel,
monitorCheckInterval: overrides.monitorCheckInterval ?? _defaultInterval,
remoteLoggingEnabled: overrides.remoteLoggingEnabled ?? _defaultRemoteLoggingEnabled,
);
}
}
class FeatureChecker {
const FeatureChecker(this._access);
final FeatureAccess _access;
/// Returns `true` if the given [feature] is enabled, otherwise `false`.
bool isEnabled(FeatureFlag feature) {
final isEnabled = _resolve(feature);
_logger.fine('Feature flag resolution: $feature = $isEnabled');
return isEnabled;
}
bool _resolve(FeatureFlag feature) {
return switch (feature) {
FeatureFlag.voicemail => _access.settingsConfig.voicemailsEnabled,
};
}
}