repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/icon_text.dart
import 'package:flutter/material.dart'; class IconText extends StatelessWidget { const IconText({ super.key, required this.icon, required this.label, this.padding = const EdgeInsets.all(8), this.horizontalPadding = const EdgeInsets.only(left: 8), this.brightness, }); final Widget icon; final Widget label; final EdgeInsets padding; final EdgeInsets horizontalPadding; final Brightness? brightness; @override Widget build(BuildContext context) { final content = Padding( padding: padding, child: Row( children: [ icon, Expanded( child: Padding( padding: horizontalPadding, child: label, ), ), ], ), ); return brightness != null ? Theme(data: ThemeData(brightness: brightness), child: content) : content; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/password_field.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class PasswordField extends StatefulWidget { const PasswordField({ super.key, required this.controller, this.labelText, this.hintText, this.onChanged, this.autofocus = false, this.cupertinoShowLabel = true, this.onSubmitted, }); final TextEditingController? controller; final String? labelText; final String? hintText; final ValueChanged<String>? onChanged; final ValueChanged<String>? onSubmitted; final bool autofocus; final bool cupertinoShowLabel; @override State<PasswordField> createState() => _PasswordFieldState(); } class _PasswordFieldState extends State<PasswordField> { bool _obscureText = true; @override Widget build(BuildContext context) => DecoratedPlatformTextField( controller: widget.controller, obscureText: _obscureText, onChanged: widget.onChanged, onSubmitted: widget.onSubmitted, autofocus: widget.autofocus, cupertinoShowLabel: widget.cupertinoShowLabel, decoration: InputDecoration( hintText: widget.hintText, labelText: widget.labelText, suffixIcon: PlatformIconButton( icon: Icon(_obscureText ? Icons.lock_open : Icons.lock), onPressed: () { setState( () => _obscureText = !_obscureText, ); }, cupertino: (context, platform) => CupertinoIconButtonData( padding: const EdgeInsets.fromLTRB(0, 0, 5, 2), icon: Icon( _obscureText ? Icons.lock_open : Icons.lock, color: CupertinoColors.secondaryLabel, size: 20, ), ), ), ), ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/mailbox_selector.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/model.dart'; import '../mail/provider.dart'; class MailboxSelector extends ConsumerWidget { const MailboxSelector({ super.key, required this.account, this.showRoot = true, this.mailbox, required this.onChanged, }); final Account account; final bool showRoot; final Mailbox? mailbox; final void Function(Mailbox? mailbox) onChanged; @override Widget build(BuildContext context, WidgetRef ref) { final mailboxTreeData = ref.watch(mailboxTreeProvider(account: account)); return mailboxTreeData.when( loading: () => const Center(child: PlatformProgressIndicator()), error: (error, stack) => Center(child: Text('$error')), data: (mailboxTree) { final mailboxes = mailboxTree.flatten((box) => !(box?.isNotSelectable ?? true)); final items = mailboxes .map( (box) => DropdownMenuItem(value: box, child: Text(box?.path ?? '')), ) .toList(); if (showRoot) { final first = mailboxes.first; if (first != null) { items.insert( 0, DropdownMenuItem(child: Text(first.pathSeparator)), ); } } return PlatformDropdownButton<Mailbox>( items: items, value: mailbox, onChanged: onChanged, ); }, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/ical_composer.dart
import 'package:enough_icalendar/enough_icalendar.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/provider.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../logger.dart'; import '../util/datetime.dart'; import '../util/modal_bottom_sheet_helper.dart'; /// A widget to compose an iCalendar appointment. class IcalComposer extends StatefulHookConsumerWidget { /// Creates a new [IcalComposer]. const IcalComposer({super.key, required this.appointment}); /// The appointment to edit. final VCalendar appointment; @override ConsumerState<IcalComposer> createState() => _IcalComposerState(); /// Creates a new appointment or edits an existing one. static Future<VCalendar?> createOrEditAppointment( BuildContext context, WidgetRef ref, { VCalendar? appointment, }) async { final localizations = ref.text; // final iconService = IconService.instance; final account = ref.read(currentRealAccountProvider); if (account == null) { logger.e('Unable to determine current real account'); return null; } final now = DateTime.now(); final start = DateTime(now.year, now.month, now.day, (now.hour + 1) % 24); final end = DateTime(start.year, start.month, start.day, start.hour, 30); final editAppointment = appointment ?? VCalendar.createEvent( start: start, end: end, organizerEmail: account.email, ); final result = await ModelBottomSheetHelper.showModalBottomSheet<bool>( context, editAppointment.summary ?? localizations.composeAppointmentTitle, IcalComposer(appointment: editAppointment), ); if (result ?? false) { _IcalComposerState._current.apply(); appointment = editAppointment; } return appointment; } } class _IcalComposerState extends ConsumerState<IcalComposer> { static late _IcalComposerState _current; final TextEditingController _summaryController = TextEditingController(); final TextEditingController _descriptionController = TextEditingController(); final TextEditingController _locationController = TextEditingController(); // final List<MailAddress> _participants = <MailAddress>[]; // late MailAccount _organizerAccount; late VEvent _event; DateTime? _previousStart; DateTime? _previousEnd; @override void initState() { _current = this; super.initState(); final ev = widget.appointment.event; if (ev != null) { _event = ev; _summaryController.text = ev.summary ?? ''; _descriptionController.text = ev.description ?? ''; _locationController.text = ev.location ?? ''; } else { _event = VEvent(parent: widget.appointment); widget.appointment.children.add(_event); } } @override void dispose() { apply(); _summaryController.dispose(); _descriptionController.dispose(); _locationController.dispose(); super.dispose(); } void apply() { _event ..summary = _summaryController.text ..description = _descriptionController.text.isNotEmpty ? _descriptionController.text : null ..location = _locationController.text.isNotEmpty ? _locationController.text : null; } @override Widget build(BuildContext context) { final localizations = ref.text; final end = _event.end; final start = _event.start ?? DateTime.now(); final isAllDay = _event.isAllDayEvent ?? false; final recurrenceRule = _event.recurrenceRule; final theme = Theme.of(context); return Material( child: Padding( padding: const EdgeInsets.all(8), child: Column( children: [ DecoratedPlatformTextField( controller: _summaryController, decoration: InputDecoration( labelText: localizations.icalendarLabelSummary, ), cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: _descriptionController, keyboardType: TextInputType.multiline, minLines: 3, maxLines: 8, decoration: InputDecoration( labelText: localizations.icalendarLabelDescription, ), cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: _locationController, decoration: InputDecoration( labelText: localizations.icalendarLabelLocation, ), cupertinoAlignLabelOnTop: true, ), Padding( padding: const EdgeInsets.fromLTRB(8, 16, 8, 0), child: Text( localizations.icalendarLabelStart, style: theme.textTheme.bodySmall, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: _DateTimePicker( dateTime: start, onlyDate: isAllDay, onChanged: (dateTime) { if (end != null) { final diff = end.difference(start); _event.end = dateTime.add(diff); } setState(() { _event.start = dateTime; }); }, ), ), if (!isAllDay) ...[ Padding( padding: const EdgeInsets.fromLTRB(8, 16, 8, 0), child: Text( localizations.icalendarLabelEnd, style: theme.textTheme.bodySmall, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: _DateTimePicker( dateTime: end, onChanged: (dateTime) { setState(() { _event.end = dateTime; }); }, ), ), ], PlatformCheckboxListTile( value: isAllDay, title: Text(localizations.composeAppointmentLabelAllDayEvent), onChanged: (value) { if (value ?? false) { _previousStart = start; _previousEnd = end; _event ..end = null ..start = DateTime(start.year, start.month, start.day) ..duration = IsoDuration(days: 1); } else { _event ..duration = null ..start = _previousStart ..end = _previousEnd; } setState(() { _event.isAllDayEvent = value; }); }, ), const Divider(), PlatformListTile( title: Text(localizations.composeAppointmentLabelRepeat), trailing: recurrenceRule == null ? Text(localizations.composeAppointmentLabelRepeatOptionNever) : null, subtitle: recurrenceRule == null ? null : Text( recurrenceRule.toHumanReadableText( languageCode: localizations.localeName, startDate: start, ), style: theme.textTheme.bodySmall, ), onTap: () async { final result = await _RecurrenceComposer.createOrEditRecurrence( ref, context, recurrenceRule, start, ); setState(() { _event.recurrenceRule = result; }); }, ), ], ), ), ); } } enum _RepeatFrequency { never, daily, weekly, monthly, yearly } extension _ExtensionRepeatFrequency on _RepeatFrequency { RecurrenceFrequency? get recurrenceFrequency { switch (this) { case _RepeatFrequency.never: return null; case _RepeatFrequency.daily: return RecurrenceFrequency.daily; case _RepeatFrequency.weekly: return RecurrenceFrequency.weekly; case _RepeatFrequency.monthly: return RecurrenceFrequency.monthly; case _RepeatFrequency.yearly: return RecurrenceFrequency.yearly; } } String localization(AppLocalizations localizations) { switch (this) { case _RepeatFrequency.never: return localizations.composeAppointmentLabelRepeatOptionNever; case _RepeatFrequency.daily: return localizations.composeAppointmentLabelRepeatOptionDaily; case _RepeatFrequency.weekly: return localizations.composeAppointmentLabelRepeatOptionWeekly; case _RepeatFrequency.monthly: return localizations.composeAppointmentLabelRepeatOptionMonthly; case _RepeatFrequency.yearly: return localizations.composeAppointmentLabelRepeatOptionYearly; } } } extension _ExtensionRecurrenceFrequency on RecurrenceFrequency { _RepeatFrequency get repeatFrequency { switch (this) { case RecurrenceFrequency.secondly: case RecurrenceFrequency.minutely: case RecurrenceFrequency.hourly: case RecurrenceFrequency.daily: return _RepeatFrequency.daily; case RecurrenceFrequency.weekly: return _RepeatFrequency.weekly; case RecurrenceFrequency.monthly: return _RepeatFrequency.monthly; case RecurrenceFrequency.yearly: return _RepeatFrequency.yearly; } } IsoDuration? get recommendedUntil { switch (this) { case RecurrenceFrequency.secondly: case RecurrenceFrequency.minutely: case RecurrenceFrequency.hourly: return null; case RecurrenceFrequency.daily: return IsoDuration(months: 3); case RecurrenceFrequency.weekly: return IsoDuration(months: 6); case RecurrenceFrequency.monthly: return IsoDuration(years: 1); case RecurrenceFrequency.yearly: return null; } } } class _DateTimePicker extends ConsumerWidget { const _DateTimePicker({ required this.dateTime, required this.onChanged, this.onlyDate = false, }); final DateTime? dateTime; final void Function(DateTime newDateTime) onChanged; final bool onlyDate; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final dt = dateTime; return Row( children: [ // set date button: PlatformTextButton( child: Text( dt == null ? localizations.composeAppointmentLabelDay : ref.formatDate(dt.toLocal(), useLongFormat: true), ), onPressed: () async { FocusScope.of(context).unfocus(); final initialDate = dt ?? DateTime.now(); final firstDate = DateTime.now(); final lastDate = DateTime(firstDate.year + 10, firstDate.month, firstDate.day); final newStartDate = await showPlatformDatePicker( context: context, initialDate: initialDate, firstDate: firstDate, lastDate: lastDate, ); if (newStartDate != null) { final withTimeOfDay = newStartDate.withTimeOfDay(initialDate.toTimeOfDay()); onChanged(withTimeOfDay); } }, ), if (!onlyDate) // set time button: PlatformTextButton( child: Text( dt == null ? localizations.composeAppointmentLabelTime : context.formatTimeOfDay( TimeOfDay.fromDateTime(dt.toLocal()), ), ), onPressed: () async { FocusScope.of(context).unfocus(); final initialDateTime = dt ?? DateTime.now(); final initialTime = initialDateTime.toTimeOfDay(); final newStartTime = await showPlatformTimePicker( context: context, initialTime: initialTime, ); if (newStartTime != null) { final withTimeOfDay = initialDateTime.withTimeOfDay(newStartTime); onChanged(withTimeOfDay); } }, ), ], ); } } class _RecurrenceComposer extends StatefulHookConsumerWidget { const _RecurrenceComposer({ this.recurrenceRule, required this.startDate, }); final Recurrence? recurrenceRule; final DateTime startDate; @override ConsumerState<_RecurrenceComposer> createState() => _RecurrenceComposerState(); static Future<Recurrence?> createOrEditRecurrence( WidgetRef ref, BuildContext context, Recurrence? recurrenceRule, DateTime startDate, ) async { final localizations = ref.text; // final iconService = IconService.instance; final result = await ModelBottomSheetHelper.showModalBottomSheet<bool>( context, localizations.composeAppointmentLabelRepeat, _RecurrenceComposer( recurrenceRule: recurrenceRule, startDate: startDate, ), ); return result ?? false ? _RecurrenceComposerState._currentState._recurrenceRule : recurrenceRule; } } class _RecurrenceComposerState extends ConsumerState<_RecurrenceComposer> { static late _RecurrenceComposerState _currentState; Recurrence? _recurrenceRule; _RepeatFrequency _repeatFrequency = _RepeatFrequency.never; DateTime? _recommendationDate; @override void initState() { _currentState = this; super.initState(); final rule = widget.recurrenceRule; _recurrenceRule = rule; if (rule != null) { _repeatFrequency = rule.frequency.repeatFrequency; } } @override Widget build(BuildContext context) { final localizations = ref.text; final rule = _recurrenceRule; return Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: const EdgeInsets.all(8), child: Text( localizations.composeAppointmentRecurrenceFrequencyLabel, ), ), PlatformDropdownButton<_RepeatFrequency>( items: _RepeatFrequency.values .map((rf) => DropdownMenuItem<_RepeatFrequency>( value: rf, child: Text(rf.localization(localizations)), )) .toList(), onChanged: (freq) { if (freq == null || freq == _RepeatFrequency.never) { setState(() { _repeatFrequency = _RepeatFrequency.never; _recurrenceRule = null; }); return; } DateTime? until; final duration = freq.recurrenceFrequency?.recommendedUntil; if (duration == null) { _recommendationDate = null; } else { until = duration.addTo(widget.startDate); _recommendationDate = until; } var newRule = (rule != null) ? rule.copyWith( frequency: freq.recurrenceFrequency, until: until, copyByRules: false, copyUntil: false, ) : Recurrence( freq.recurrenceFrequency ?? RecurrenceFrequency.daily, until: until, ); if (newRule.frequency == RecurrenceFrequency.monthly) { final monthly = _DayOfMonthSelector.updateMonthlyRecurrence( newRule, widget.startDate, ); if (monthly != null) { newRule = monthly; } } setState(() { _repeatFrequency = freq; _recurrenceRule = newRule; }); }, value: _repeatFrequency, ), ], ), if (rule != null) ...[ Row( children: [ Padding( padding: const EdgeInsets.all(8), child: Text( localizations.composeAppointmentRecurrenceIntervalLabel, ), ), PlatformDropdownButton<int>( items: List.generate( 10, (index) => DropdownMenuItem<int>( value: index + 1, child: Text('${index + 1}'), ), ), onChanged: (interval) { setState(() { _recurrenceRule = rule.copyWith(interval: interval); }); }, value: rule.interval, ), ], ), if (rule.frequency == RecurrenceFrequency.weekly) ...[ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.composeAppointmentRecurrenceDaysLabel), ), _WeekDaySelector( recurrence: rule, startDate: widget.startDate, onChanged: (rules) { Recurrence value; value = rules == null ? rule.copyWith(copyByRules: false) : rule.copyWith(byWeekDay: rules); setState(() { _recurrenceRule = value; }); }, ), ] else if (rule.frequency == RecurrenceFrequency.monthly) ...[ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.composeAppointmentRecurrenceDaysLabel), ), _DayOfMonthSelector( recurrence: rule, startDate: widget.startDate, onChanged: (value) { setState(() { _recurrenceRule = value; }); }, ), ], PlatformListTile( title: Text(localizations.composeAppointmentRecurrenceUntilLabel), trailing: Text( rule.until == null ? localizations .composeAppointmentRecurrenceUntilOptionUnlimited : rule.until == _recommendationDate ? localizations .composeAppointmentRecurrenceUntilOptionRecommended( ref.formatIsoDuration( rule.frequency.recommendedUntil ?? IsoDuration(), ), ) : ref.formatDate( rule.until, useLongFormat: true, ), ), onTap: () async { final until = await _UntilComposer.createOrEditUntil( context, ref, widget.startDate, rule.until, rule.frequency.recommendedUntil, ); final newRule = (until == null) ? rule.copyWithout(RecurrenceAttribute.until) : rule.copyWith(until: until); setState(() { _recurrenceRule = newRule; }); }, ), const Divider(), Padding( padding: const EdgeInsets.all(8), child: Text(rule.toHumanReadableText( languageCode: localizations.localeName, startDate: widget.startDate, )), ), ], ], ), ); } } class _WeekDaySelector extends StatefulHookConsumerWidget { const _WeekDaySelector({ required this.recurrence, required this.onChanged, required this.startDate, }); final Recurrence recurrence; final DateTime startDate; final void Function(List<ByDayRule>? rules) onChanged; @override ConsumerState<_WeekDaySelector> createState() => _WeekDaySelectorState(); } class _WeekDaySelectorState extends ConsumerState<_WeekDaySelector> { late List<WeekDay> _weekdays; final _selectedDays = <bool>[false, false, false, false, false, false, false]; @override void initState() { super.initState(); _weekdays = ref.formatWeekDays(abbreviate: true); final byWeekDays = widget.recurrence.byWeekDay; if (byWeekDays != null) { final int firstDayOfWeek = ref.firstDayOfWeek; for (int i = 0; i < 7; i++) { final day = ((firstDayOfWeek + i) <= 7) ? (firstDayOfWeek + i) : ((firstDayOfWeek + i) - 7); final bool isSelected = byWeekDays.any((dayRule) => dayRule.weekday == day); _selectedDays[i] = isSelected; } } _selectStartDateWeekDay(); } void _selectStartDateWeekDay() { final startDateWeekDay = widget.startDate.weekday; final index = _weekdays.indexWhere((weekDay) => weekDay.day == startDateWeekDay); _selectedDays[index] = true; } void _toggle(int index) { final day = _weekdays[index].day; var isSelected = !_selectedDays[index]; var rules = widget.recurrence.byWeekDay; if (isSelected) { if (rules == null) { rules = [ByDayRule(day), ByDayRule(widget.startDate.weekday)]; } else { rules.add(ByDayRule(day)); } } else { if (rules != null) { rules.removeWhere((rule) => rule.weekday == day); if (rules.isEmpty || rules.length == 1 && rules[0].weekday == widget.startDate.weekday) { rules = null; // re-select weekday from start day: _selectStartDateWeekDay(); } } else if (day == widget.startDate.weekday) { isSelected = true; } } widget.onChanged(rules); setState(() => _selectedDays[index] = isSelected); } @override Widget build(BuildContext context) => FittedBox( child: PlatformToggleButtons( isSelected: _selectedDays, onPressed: _toggle, children: _weekdays .map((day) => Padding( padding: const EdgeInsets.all(8), child: Text(day.name), )) .toList(), ), ); } enum _DayOfMonthOption { dayOfMonth, dayInNumberedWeek } class _DayOfMonthSelector extends StatefulHookConsumerWidget { const _DayOfMonthSelector({ required this.recurrence, required this.startDate, required this.onChanged, }); final Recurrence recurrence; final DateTime startDate; final void Function(Recurrence recurrence) onChanged; @override ConsumerState<_DayOfMonthSelector> createState() => _DayOfMonthSelectorState(); static Recurrence? updateMonthlyRecurrence( Recurrence recurrence, DateTime startDate, ) { if (recurrence.hasByMonthDay || recurrence.hasByWeekDay) { return null; } final day = startDate.day; final weekday = startDate.weekday; var week = (day / 7).ceil(); if (week > 3) { // is the last or the second last weekday? final daysInMonth = DateTime(startDate.year, startDate.month + 1, 0).day; week = -((daysInMonth - day) / 7).ceil(); } final rule = ByDayRule(weekday, week: week); return recurrence.copyWith(byWeekDay: [rule], copyByRules: false); } } class _DayOfMonthSelectorState extends ConsumerState<_DayOfMonthSelector> { late _DayOfMonthOption _option; ByDayRule? _byDayRule; WeekDay? _currentWeekday; late List<WeekDay> _weekdays; @override void initState() { super.initState(); _weekdays = ref.formatWeekDays(); if (widget.recurrence.hasByMonthDay) { _option = _DayOfMonthOption.dayOfMonth; } else { var recurrence = widget.recurrence; if (!widget.recurrence.hasByWeekDay) { recurrence = _DayOfMonthSelector.updateMonthlyRecurrence( recurrence, widget.startDate, ) ?? recurrence; } _option = _DayOfMonthOption.dayInNumberedWeek; final rule = recurrence.byWeekDay?.first; _byDayRule = rule; _currentWeekday = _weekdays.firstWhere((wd) => wd.day == rule?.weekday); } } @override Widget build(BuildContext context) { final localizations = ref.text; final rule = _byDayRule; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ PlatformRadioListTile<_DayOfMonthOption>( groupValue: _option, value: _DayOfMonthOption.dayOfMonth, title: Text( localizations.composeAppointmentRecurrenceMonthlyOnDayOfMonth( widget.startDate.day, ), ), onChanged: (value) { if (value == null) { return; } setState(() { _option = value; }); widget.onChanged( widget.recurrence.copyWith( byMonthDay: [widget.startDate.day], copyByRules: false, ), ); }, ), PlatformRadioListTile<_DayOfMonthOption>( groupValue: _option, value: _DayOfMonthOption.dayInNumberedWeek, title: Text(localizations.composeAppointmentRecurrenceMonthlyOnWeekDay), onChanged: (value) { if (value == null) { return; } if (_byDayRule == null) { final recurrence = _DayOfMonthSelector.updateMonthlyRecurrence( widget.recurrence.copyWith(copyByRules: false), widget.startDate, ) ?? widget.recurrence.copyWith( byWeekDay: [ByDayRule(widget.startDate.weekday)], ); final rule = recurrence.byWeekDay?.first; _byDayRule = rule; _currentWeekday = _weekdays.firstWhere((wd) => wd.day == rule?.weekday); widget.onChanged(recurrence); } setState(() { _option = value; }); }, ), if (_option == _DayOfMonthOption.dayInNumberedWeek && rule != null) ...[ Padding( padding: const EdgeInsets.fromLTRB(32, 8, 8, 32), child: Row( children: [ PlatformDropdownButton<int>( items: [ DropdownMenuItem<int>( value: 1, child: Text(localizations.composeAppointmentRecurrenceFirst), ), DropdownMenuItem<int>( value: 2, child: Text( localizations.composeAppointmentRecurrenceSecond, ), ), DropdownMenuItem<int>( value: 3, child: Text( localizations.composeAppointmentRecurrenceThird, ), ), DropdownMenuItem<int>( value: -1, child: Text(localizations.composeAppointmentRecurrenceLast), ), DropdownMenuItem<int>( value: -2, child: Text( localizations.composeAppointmentRecurrenceSecondLast, ), ), ], value: rule.week, onChanged: (value) { final newRule = ByDayRule(rule.weekday, week: value); _byDayRule = newRule; final recurrence = widget.recurrence.copyWith(byWeekDay: [newRule]); widget.onChanged(recurrence); }, ), const Padding( padding: EdgeInsets.all(8), ), PlatformDropdownButton<WeekDay>( items: _weekdays .map((wd) => DropdownMenuItem<WeekDay>( value: wd, child: Text(wd.name), )) .toList(), value: _currentWeekday, onChanged: (value) { if (value == null) { return; } final newRule = ByDayRule(value.day, week: rule.week); _byDayRule = newRule; final recurrence = widget.recurrence.copyWith(byWeekDay: [newRule]); widget.onChanged(recurrence); }, ), ], ), ), ], ], ); } } class _UntilComposer extends StatefulHookConsumerWidget { const _UntilComposer({ required this.start, this.until, this.recommendation, }); final DateTime start; final DateTime? until; final IsoDuration? recommendation; @override ConsumerState<_UntilComposer> createState() => _UntilComposerState(); static Future<DateTime?> createOrEditUntil( BuildContext context, WidgetRef ref, DateTime start, DateTime? until, IsoDuration? recommendation, ) async { final localizations = ref.text; // final iconService = IconService.instance; final result = await ModelBottomSheetHelper.showModalBottomSheet<bool>( context, localizations.composeAppointmentRecurrenceUntilLabel, _UntilComposer( start: start, until: until, recommendation: recommendation, ), ); return (result ?? false) ? _UntilComposerState._currentState._until : until; } } class _UntilComposerState extends ConsumerState<_UntilComposer> { static late _UntilComposerState _currentState; late _UntilOption _option; DateTime? _recommendationDate; DateTime? _until; @override void initState() { super.initState(); _currentState = this; _until = widget.until; final recommendation = widget.recommendation; if (recommendation != null) { _recommendationDate = recommendation.addTo(widget.start); } if (_until == null) { _option = _UntilOption.unlimited; } else if (_until == _recommendationDate) { _option = _UntilOption.recommendation; } else { _option = _UntilOption.date; } } @override Widget build(BuildContext context) { // final i18nService = locator<I18nService>(); final localizations = ref.text; final theme = Theme.of(context); return Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ for (final value in _UntilOption.values) if (_recommendationDate != null || value != _UntilOption.recommendation) PlatformRadioListTile<_UntilOption>( groupValue: _option, value: value, onChanged: _onChanged, title: Text( value.localization( ref, localizations, widget.recommendation, ), ), ), if (_option == _UntilOption.date) ...[ Padding( padding: const EdgeInsets.fromLTRB(8, 16, 8, 0), child: Text( localizations.composeAppointmentRecurrenceUntilLabel, style: theme.textTheme.bodySmall, ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: _DateTimePicker( dateTime: _until, onlyDate: true, onChanged: (dateTime) { setState(() { _until = dateTime; }); }, ), ), ], ], ), ); } void _onChanged(_UntilOption? value) { if (value != null) { switch (value) { case _UntilOption.unlimited: _until = null; break; case _UntilOption.recommendation: _until = _recommendationDate; break; case _UntilOption.date: break; } setState(() { _option = value; }); } } } enum _UntilOption { unlimited, recommendation, date } extension _ExtensionUntilOption on _UntilOption { String localization( WidgetRef ref, AppLocalizations localizations, IsoDuration? recommendation, ) { switch (this) { case _UntilOption.unlimited: return localizations.composeAppointmentRecurrenceUntilOptionUnlimited; case _UntilOption.recommendation: final duration = recommendation == null ? '' : ref.formatIsoDuration(recommendation); return localizations .composeAppointmentRecurrenceUntilOptionRecommended(duration); case _UntilOption.date: return localizations .composeAppointmentRecurrenceUntilOptionSpecificDate; } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/cupertino_status_bar.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../scaffold_messenger/service.dart'; /// Status bar for cupertino. /// /// Contains compose action and can display snackbar notifications on ios. class CupertinoStatusBar extends StatefulHookConsumerWidget { const CupertinoStatusBar({ super.key, this.leftAction, this.rightAction, this.info, }); static const _statusTextStyle = TextStyle(fontSize: 10); final Widget? leftAction; final Widget? rightAction; final Widget? info; @override ConsumerState<CupertinoStatusBar> createState() => CupertinoStatusBarState(); static Widget? createInfo(String? text) => (text == null) ? null : Text( text, style: _statusTextStyle, ); } class CupertinoStatusBarState extends ConsumerState<CupertinoStatusBar> { Widget? _status; Widget? _statusAction; late double _statusOpacity; @override void initState() { super.initState(); ScaffoldMessengerService.instance.statusBarState = this; } @override void dispose() { super.dispose(); ScaffoldMessengerService.instance.popStatusBarState(); } @override Widget build(BuildContext context) { final lAction = widget.leftAction; final sAction = (_statusAction == null) ? null : AnimatedOpacity( opacity: _statusOpacity, duration: const Duration(milliseconds: 400), child: _statusAction, ); final rAction = (sAction != null && widget.rightAction != null) ? AnimatedOpacity( opacity: 1.0 - _statusOpacity, duration: const Duration(milliseconds: 400), child: widget.rightAction, ) : widget.rightAction; final middle = (_status != null) ? AnimatedOpacity( opacity: _statusOpacity, duration: const Duration(milliseconds: 400), child: _status, ) : widget.info ?? Container(); return CupertinoBar( blurBackground: true, backgroundOpacity: 0.8, child: SafeArea( top: false, child: SizedBox( height: 44, child: Stack( fit: StackFit.passthrough, children: [ Align( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: middle, ), ), if (lAction != null) Align( alignment: Alignment.centerLeft, child: lAction, ), if (rAction != null) Align( alignment: Alignment.centerRight, child: rAction, ), if (sAction != null) Align( alignment: Alignment.centerRight, child: sAction, ), ], ), ), ), ); } Future<void> showTextStatus(String text, {Function()? undo}) async { final notification = Text( text, style: CupertinoStatusBar._statusTextStyle, ); if (undo != null) { _statusAction = Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: CupertinoButton.filled( padding: const EdgeInsets.all(8), minSize: 20, child: Text( ref.text.actionUndo, style: CupertinoStatusBar._statusTextStyle, ), onPressed: () { setState(() { _status = null; _statusAction = null; }); undo(); }, ), ); } else if (_statusAction != null) { _statusAction = null; } setState(() { _statusOpacity = 1.0; _status = notification; }); await Future.delayed(const Duration(seconds: 4)); if (_status == notification && mounted) { setState(() { _statusOpacity = 0.0; }); await Future.delayed(const Duration(milliseconds: 500)); if (_status == notification && mounted) { setState(() { _status = null; _statusAction = null; }); } } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/account_selector.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/model.dart'; import '../account/provider.dart'; class AccountSelector extends ConsumerWidget { const AccountSelector({ super.key, required this.onChanged, required this.account, this.excludeAccountsWithErrors = true, }); final RealAccount? account; final bool excludeAccountsWithErrors; final void Function(RealAccount account) onChanged; @override Widget build(BuildContext context, WidgetRef ref) { final allAccounts = ref.watch(realAccountsProvider); final accounts = excludeAccountsWithErrors ? allAccounts.where((account) => !account.hasError).toList() : allAccounts; return PlatformDropdownButton<RealAccount>( value: account, items: accounts .map((account) => DropdownMenuItem<RealAccount>( value: account, child: Text(account.name), )) .toList(), onChanged: (account) { if (account != null) { onChanged(account); } }, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/text_with_links.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; /// Displays text with links that can be tapped. class TextWithLinks extends StatelessWidget { /// Creates a new text with links widget. const TextWithLinks({super.key, required this.text, this.style}); /// The text to display. final String text; /// The style to use for the text. final TextStyle? style; static final RegExp _schemeRegEx = RegExp('[a-z]{3,6}://'); // not a perfect but good enough regular expression to match URLs in text. // It also matches a space at the beginning and a dot at the end, // so this is filtered out manually in the found matches static final RegExp _linkRegEx = RegExp( r'(([a-z]{3,6}:\/\/)|(^|\s))([a-zA-Z0-9\-]+\.)+[a-z]{2,13}([\?\/]+[\.\?\=\&\%\/\w\+\-]*)?', ); @override Widget build(BuildContext context) { final theme = Theme.of(context); final textStyle = style ?? theme.textTheme.bodyMedium ?? TextStyle( color: theme.brightness == Brightness.light ? Colors.black : Colors.white, ); final matches = _linkRegEx.allMatches(text); if (matches.isEmpty) { return SelectableText(text, style: textStyle); } final linkStyle = textStyle.copyWith( decoration: TextDecoration.underline, color: theme.colorScheme.secondary, ); final spans = <TextSpan>[]; var end = 0; for (final match in matches) { if (match.end < text.length && text[match.end] == '@') { // this is an email address, abort abort! ;-) continue; } final originalGroup = match.group(0) ?? ''; final group = originalGroup.trimLeft(); final start = match.start + originalGroup.length - group.length; spans.add(TextSpan(text: text.substring(end, start))); final endsWithDot = group.endsWith('.'); final urlText = endsWithDot ? group.substring(0, group.length - 1) : group; final url = !group.startsWith(_schemeRegEx) ? 'https://$urlText' : urlText; spans.add( TextSpan( text: urlText, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () => launchUrl(Uri.parse(url)), ), ); end = endsWithDot ? match.end - 1 : match.end; } if (end < text.length) { spans.add(TextSpan(text: text.substring(end))); } return SelectableText.rich( TextSpan( children: spans, style: textStyle, ), ); } } /// Displays text with links that can be tapped. class TextWithNamedLinks extends StatelessWidget { /// Creates a new text with links widget. const TextWithNamedLinks({super.key, required this.parts, this.style}); /// The text parts to display. final List<TextLink> parts; /// The style to use for the text. final TextStyle? style; @override Widget build(BuildContext context) { final theme = Theme.of(context); final textStyle = style ?? theme.textTheme.bodyMedium ?? TextStyle( color: theme.brightness == Brightness.light ? Colors.black : Colors.white, ); final linkStyle = textStyle.copyWith( decoration: TextDecoration.underline, color: theme.colorScheme.secondary, ); final spans = <TextSpan>[]; for (final part in parts) { final url = part.url; final callback = part.callback; if (url != null || callback != null) { spans.add( TextSpan( text: part.text, style: linkStyle, recognizer: TapGestureRecognizer() ..onTap = () { if (callback != null) { callback(); } else { launchUrl(Uri.parse(url ?? '')); } }, ), ); } else { spans.add(TextSpan(text: part.text)); } } return SelectableText.rich( TextSpan(children: spans, style: textStyle), ); } } /// A link in a text. class TextLink { /// Creates a new text link. const TextLink(this.text, [this.url]) : callback = null; /// Creates a new text link with a callback. const TextLink.callback(this.text, this.callback) : url = null; /// The text to display. final String text; /// The URL to open when the link is tapped. final String? url; /// The callback to call when the link is tapped. final void Function()? callback; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/message_actions.dart
import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/model.dart'; import '../contact/provider.dart'; import '../localization/extension.dart'; import '../models/compose_data.dart'; import '../models/message.dart'; import '../notification/service.dart'; import '../routes/routes.dart'; import '../scaffold_messenger/service.dart'; import '../settings/model.dart'; import '../settings/provider.dart'; import '../settings/theme/icon_service.dart'; import '../util/localized_dialog_helper.dart'; import '../util/validator.dart'; import 'icon_text.dart'; import 'mailbox_tree.dart'; import 'recipient_input_field.dart'; enum _OverflowMenuChoice { reply, replyAll, forward, forwardAsAttachment, forwardAttachments, delete, inbox, seen, flag, move, junk, archive, redirect, addNotification, } /// Displays actions for a single message. class MessageActions extends HookConsumerWidget { /// Creates a [MessageActions] widget. const MessageActions({super.key, required this.message}); /// The message to display actions for. final Message message; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final attachments = message.attachments; final iconService = IconService.instance; void onOverflowChoiceSelected(_OverflowMenuChoice result) { switch (result) { case _OverflowMenuChoice.reply: _reply(context, ref); break; case _OverflowMenuChoice.replyAll: _replyAll(context, ref); break; case _OverflowMenuChoice.forward: _forward(context, ref); break; case _OverflowMenuChoice.forwardAsAttachment: _forwardAsAttachment(context, ref); break; case _OverflowMenuChoice.forwardAttachments: _forwardAttachments(context, ref); break; case _OverflowMenuChoice.delete: _delete(context, ref); break; case _OverflowMenuChoice.inbox: _moveToInbox(context, ref); break; case _OverflowMenuChoice.seen: _toggleSeen(); break; case _OverflowMenuChoice.flag: _toggleFlagged(); break; case _OverflowMenuChoice.move: _move(context, ref); break; case _OverflowMenuChoice.junk: _moveJunk(context, ref); break; case _OverflowMenuChoice.archive: _moveArchive(context, ref); break; case _OverflowMenuChoice.redirect: _redirectMessage(context, ref); break; case _OverflowMenuChoice.addNotification: _addNotification(); break; } } return PlatformBottomBar( cupertinoBackgroundOpacity: 0.8, child: SafeArea( top: false, child: ListenableBuilder( listenable: message, builder: (context, child) => Row( children: [ if (!message.isEmbedded) ...[ DensePlatformIconButton( icon: Icon(iconService.getMessageIsSeen(message.isSeen)), onPressed: _toggleSeen, ), DensePlatformIconButton( icon: Icon(iconService.getMessageIsFlagged(message.isFlagged)), onPressed: _toggleFlagged, ), ], const Spacer(), DensePlatformIconButton( icon: Icon(iconService.messageActionReply), onPressed: () => _reply(context, ref), ), DensePlatformIconButton( icon: Icon(iconService.messageActionReplyAll), onPressed: () => _replyAll(context, ref), ), DensePlatformIconButton( icon: Icon(iconService.messageActionForward), onPressed: () => _forward(context, ref), ), if (message.source.isTrash) DensePlatformIconButton( icon: Icon(iconService.messageActionMoveToInbox), onPressed: () => _moveToInbox(context, ref), ) else if (!message.isEmbedded) DensePlatformIconButton( icon: Icon(iconService.messageActionDelete), onPressed: () => _delete(context, ref), ), PlatformPopupMenuButton<_OverflowMenuChoice>( onSelected: onOverflowChoiceSelected, itemBuilder: (context) => [ PlatformPopupMenuItem( value: _OverflowMenuChoice.reply, child: IconText( icon: Icon(iconService.messageActionReply), label: Text(localizations.messageActionReply), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.replyAll, child: IconText( icon: Icon(iconService.messageActionReplyAll), label: Text(localizations.messageActionReplyAll), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.forward, child: IconText( icon: Icon(iconService.messageActionForward), label: Text(localizations.messageActionForward), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.forwardAsAttachment, child: IconText( icon: Icon(iconService.messageActionForwardAsAttachment), label: Text(localizations.messageActionForwardAsAttachment), ), ), if (attachments.isNotEmpty) PlatformPopupMenuItem( value: _OverflowMenuChoice.forwardAttachments, child: IconText( icon: Icon(iconService.messageActionForwardAttachments), label: Text( localizations.messageActionForwardAttachments( attachments.length, ), ), ), ), if (message.source.isTrash) PlatformPopupMenuItem( value: _OverflowMenuChoice.inbox, child: IconText( icon: Icon(iconService.messageActionMoveToInbox), label: Text(localizations.messageActionMoveToInbox), ), ) else if (!message.isEmbedded) PlatformPopupMenuItem( value: _OverflowMenuChoice.delete, child: IconText( icon: Icon(iconService.messageActionDelete), label: Text(localizations.messageActionDelete), ), ), if (!message.isEmbedded) ...[ const PlatformPopupDivider(), PlatformPopupMenuItem( value: _OverflowMenuChoice.seen, child: IconText( icon: Icon(iconService.getMessageIsSeen(message.isSeen)), label: Text( message.isSeen ? localizations.messageStatusSeen : localizations.messageStatusUnseen, ), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.flag, child: IconText( icon: Icon( iconService.getMessageIsFlagged(message.isFlagged), ), label: Text( message.isFlagged ? localizations.messageStatusFlagged : localizations.messageStatusUnflagged, ), ), ), if (message.source.supportsMessageFolders) ...[ const PlatformPopupDivider(), PlatformPopupMenuItem( value: _OverflowMenuChoice.move, child: IconText( icon: Icon(iconService.messageActionMove), label: Text(localizations.messageActionMove), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.junk, child: IconText( icon: Icon(message.source.isJunk ? iconService.messageActionMoveFromJunkToInbox : iconService.messageActionMoveToJunk), label: Text( message.source.isJunk ? localizations.messageActionMarkAsNotJunk : localizations.messageActionMarkAsJunk, ), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.archive, child: IconText( icon: Icon(message.source.isArchive ? iconService.messageActionMoveToInbox : iconService.messageActionArchive), label: Text( message.source.isArchive ? localizations.messageActionUnarchive : localizations.messageActionArchive, ), ), ), ], // folders are supported PlatformPopupMenuItem( value: _OverflowMenuChoice.redirect, child: IconText( icon: Icon(iconService.messageActionRedirect), label: Text( localizations.messageActionRedirect, ), ), ), PlatformPopupMenuItem( value: _OverflowMenuChoice.addNotification, child: IconText( icon: Icon(iconService.messageActionAddNotification), label: Text( localizations.messageActionAddNotification, ), ), ), ], // message is not embedded in a different message ], ), ], ), ), ), ); } // void _next() { // _navigateToMessage(message.next); // } // void _previous() { // _navigateToMessage(message.previous); // } // void _navigateToMessage(Message? message) { // if (message != null) { // locator<NavigationService>() // .push(Routes.mailDetails, arguments: message, replace: true); // } // } void _replyAll(BuildContext context, WidgetRef ref) { _reply(context, ref, all: true); } void _reply(BuildContext context, WidgetRef ref, {all = false}) { final account = message.account; final mime = message.mimeMessage; final recipientAddresses = mime.recipientAddresses; bool matchesRecipients(RealAccount account) { final aliases = [ account.email, ...account.aliases.map((alias) => alias.email), ]; for (final email in aliases) { if (recipientAddresses.contains(email)) { return true; } } return false; } final realAccount = account is RealAccount ? account : account is UnifiedAccount ? account.accounts.firstWhereOrNull(matchesRecipients) : null; final builder = MessageBuilder.prepareReplyToMessage( mime, realAccount?.fromAddress ?? account.fromAddress, aliases: realAccount?.aliases, handlePlusAliases: realAccount?.supportsPlusAliases ?? false, replyAll: all, ); _navigateToCompose(context, ref, message, builder, ComposeAction.answer); } Future<void> _redirectMessage(BuildContext context, WidgetRef ref) async { final account = message.account; if (account is RealAccount) { account.contactManager ??= await ref.read(contactsLoaderProvider(account: account).future); } if (!context.mounted) { return; } final List<MailAddress> recipients = []; final localizations = ref.text; final size = MediaQuery.sizeOf(context); final textEditingController = TextEditingController(); final redirect = await LocalizedDialogHelper.showWidgetDialog( ref, SingleChildScrollView( child: SizedBox( width: size.width - 32, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.redirectInfo, style: Theme.of(context).textTheme.bodySmall, ), RecipientInputField( addresses: recipients, contactManager: account is RealAccount ? account.contactManager : null, labelText: localizations.detailsHeaderTo, hintText: localizations.composeRecipientHint, controller: textEditingController, ), ], ), ), ), title: localizations.redirectTitle, actions: [ TextButton( child: Text(localizations.actionCancel), onPressed: () => context.pop(false), ), TextButton( child: Text(localizations.messageActionRedirect), onPressed: () { if (Validator.validateEmail(textEditingController.text)) { recipients.add(MailAddress(null, textEditingController.text)); } context.pop(true); }, ), ], ); if (!context.mounted) { return; } if (redirect == true) { if (recipients.isEmpty) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.redirectEmailInputRequired, ); } else { final mime = message.mimeMessage; if (mime.mimeData == null) { // download complete message first await message.source.fetchMessageContents(message); } try { await message.source.getMimeSource(message)?.sendMessage( mime, recipients: recipients, appendToSent: false, ); ScaffoldMessengerService.instance.showTextSnackBar( localizations, localizations.resultRedirectedSuccess, ); } on MailException catch (e, s) { if (kDebugMode) { print('message could not get redirected: $e $s'); } if (!context.mounted) { return; } await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.resultRedirectedFailure(e.message ?? '<unknown>'), ); } } } } Future<void> _delete(BuildContext context, WidgetRef ref) async { final localizations = ref.text; context.pop(); await message.source.deleteMessages( localizations, [message], localizations.resultDeleted, ); } void _move(BuildContext context, WidgetRef ref) { final localizations = ref.text; LocalizedDialogHelper.showWidgetDialog( ref, SingleChildScrollView( child: MailboxTree( account: message.account, onSelected: (mailbox) => _moveTo(context, ref, mailbox), // TODO(RV): retrieve the current selected mailbox in a different way // current: message.mailClient.selectedMailbox, ), ), title: localizations.moveTitle, defaultActions: DialogActions.cancel, ); } Future<void> _moveTo( BuildContext context, WidgetRef ref, Mailbox mailbox) async { context ..pop() // alert ..pop(); // detail view final localizations = ref.text; final source = message.source; await source.moveMessage( localizations, message, mailbox, localizations.moveSuccess(mailbox.name), ); } Future<void> _moveJunk(BuildContext context, WidgetRef ref) async { final source = message.source; if (source.isJunk) { await source.markAsNotJunk(ref.text, message); } else { NotificationService.instance.cancelNotificationForMessage(message); await source.markAsJunk(ref.text, message); } if (context.mounted) { context.pop(); } } Future<void> _moveToInbox(BuildContext context, WidgetRef ref) async { final source = message.source; final localizations = ref.text; await source.moveMessageToFlag( localizations, message, MailboxFlag.inbox, localizations.resultMovedToInbox, ); if (context.mounted) { context.pop(); } } Future<void> _moveArchive(BuildContext context, WidgetRef ref) async { final source = message.source; if (source.isArchive) { await source.moveToInbox(ref.text, message); } else { NotificationService.instance.cancelNotificationForMessage(message); await source.archive(ref.text, message); } if (context.mounted) { context.pop(); } } void _forward(BuildContext context, WidgetRef ref) { final from = message.account.fromAddress; final builder = MessageBuilder.prepareForwardMessage( message.mimeMessage, from: from, quoteMessage: false, forwardAttachments: false, ); final composeFuture = _addAttachments(message, builder); _navigateToCompose( context, ref, message, builder, ComposeAction.forward, composeFuture, ); } Future<void> _forwardAsAttachment(BuildContext context, WidgetRef ref) async { final message = this.message; final from = message.account.fromAddress; final mime = message.mimeMessage; final builder = MessageBuilder() ..from = [from] ..subject = MessageBuilder.createForwardSubject( mime.decodeSubject() ?? '', ); Future? composeFuture; if (mime.mimeData == null) { composeFuture = message.source.fetchMessageContents(message).then( builder.addMessagePart, ); } else { builder.addMessagePart(mime); } _navigateToCompose( context, ref, message, builder, ComposeAction.forward, composeFuture, ); } Future<void> _forwardAttachments(BuildContext context, WidgetRef ref) async { final message = this.message; final from = message.account.fromAddress; final mime = message.mimeMessage; final builder = MessageBuilder() ..from = [from] ..subject = MessageBuilder.createForwardSubject( mime.decodeSubject() ?? '', ); final composeFuture = _addAttachments(message, builder); _navigateToCompose( context, ref, message, builder, ComposeAction.forward, composeFuture, ); } Future? _addAttachments(Message message, MessageBuilder builder) { final attachments = message.attachments; final mime = message.mimeMessage; Future? composeFuture; if (mime.mimeData == null && attachments.length > 1) { composeFuture = message.source.fetchMessageContents(message).then( (value) { for (final attachment in attachments) { final part = value.getPart(attachment.fetchId); builder.addPart(mimePart: part); } }, ); } else { final futures = <Future>[]; for (final attachment in message.attachments) { final part = mime.getPart(attachment.fetchId); if (part != null) { builder.addPart(mimePart: part); } else { futures.add( message.source .fetchMessagePart(message, fetchId: attachment.fetchId) .then( (value) { builder.addPart(mimePart: value); }, ), ); } composeFuture = futures.isEmpty ? null : Future.wait(futures); } } return composeFuture; } Future<void> _toggleFlagged() async { final msg = message; final flagged = !msg.isFlagged; await msg.source.markAsFlagged(msg, flagged); } Future<void> _toggleSeen() async { final msg = message; final seen = !msg.isSeen; await msg.source.markAsSeen(msg, seen); } void _navigateToCompose( BuildContext context, WidgetRef ref, Message? message, MessageBuilder builder, ComposeAction action, [ Future? composeFuture, ]) { final formatPreference = ref.read(settingsProvider).replyFormatPreference; ComposeMode mode; switch (formatPreference) { case ReplyFormatPreference.alwaysHtml: mode = ComposeMode.html; break; case ReplyFormatPreference.sameFormat: if (message == null) { mode = ComposeMode.html; } else if (message.mimeMessage.hasPart(MediaSubtype.textHtml)) { mode = ComposeMode.html; } else if (message.mimeMessage.hasPart(MediaSubtype.textPlain)) { mode = ComposeMode.plainText; } else { mode = ComposeMode.html; } break; case ReplyFormatPreference.alwaysPlainText: mode = ComposeMode.plainText; break; } final data = ComposeData( [message], builder, action, future: composeFuture, composeMode: mode, ); context.pushReplacementNamed(Routes.mailCompose, extra: data); } void _addNotification() { NotificationService.instance.sendLocalNotificationForMailMessage(message); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/attachment_chip.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_mail_flutter/enough_mail_flutter.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../logger.dart'; import '../models/message.dart'; import '../routes/routes.dart'; import '../screens/media_screen.dart'; import '../settings/theme/icon_service.dart'; import '../util/localized_dialog_helper.dart'; import 'ical_interactive_media.dart'; class AttachmentChip extends StatefulHookConsumerWidget { const AttachmentChip({super.key, required this.info, required this.message}); final ContentInfo info; final Message message; @override ConsumerState<AttachmentChip> createState() => _AttachmentChipState(); } class _AttachmentChipState extends ConsumerState<AttachmentChip> { MimePart? _mimePart; bool _isDownloading = false; MediaProvider? _mediaProvider; final _width = 72.0; final _height = 72.0; @override void didChangeDependencies() { super.didChangeDependencies(); final mimeMessage = widget.message.mimeMessage; final mimePart = mimeMessage.getPart(widget.info.fetchId); _mimePart = mimePart; if (mimePart != null) { try { _mediaProvider = MimeMediaProviderFactory.fromMime(mimeMessage, mimePart); } catch (e, s) { _mediaProvider = MimeMediaProviderFactory.fromError( title: ref.text.errorTitle, text: ref.text.attachmentDecodeError(e.toString()), ); logger.e( 'Unable to decode mime-part with headers ${mimePart.headers}: $e', error: e, stackTrace: s, ); } } } @override Widget build(BuildContext context) { final mediaType = widget.info.contentType?.mediaType; final name = widget.info.fileName; final mediaProvider = _mediaProvider; if (mediaProvider == null) { final fallbackIcon = IconService.instance.getForMediaType(mediaType); return PlatformTextButton( onPressed: _isDownloading ? null : _download, child: Padding( padding: const EdgeInsets.all(4), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: _buildPreviewWidget(true, fallbackIcon, name), ), ), ); } else { return Padding( padding: const EdgeInsets.all(4), child: ClipRRect( borderRadius: BorderRadius.circular(8), child: PreviewMediaWidget( mediaProvider: mediaProvider, width: _width, height: _height, showInteractiveDelegate: _showAttachment, fallbackBuilder: _buildFallbackPreview, interactiveBuilder: _buildInteractiveMedia, interactiveFallbackBuilder: _buildInteractiveFallback, useHeroAnimation: false, ), ), ); } } Widget _buildFallbackPreview(BuildContext context, MediaProvider provider) { final fallbackIcon = IconService.instance .getForMediaType(MediaType.fromText(provider.mediaType)); return _buildPreviewWidget(false, fallbackIcon, provider.name); } Widget _buildPreviewWidget( bool includeDownloadOption, IconData iconData, String? name, ) => SizedBox( width: _width, height: _height, //color: Colors.yellow, child: Stack( children: [ Icon( iconData, size: _width, color: Colors.grey[700], ), if (name != null) Align( alignment: Alignment.bottomLeft, child: Container( width: _width, decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [Color(0x00000000), Color(0xff000000)], ), ), child: Padding( padding: const EdgeInsets.all(4), child: Text( name, overflow: TextOverflow.fade, style: const TextStyle(fontSize: 8, color: Colors.white), ), ), ), ), if (includeDownloadOption) ...[ Align( alignment: Alignment.topLeft, child: Container( width: _width, decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [Color(0x00000000), Color(0xff000000)], ), ), child: const Padding( padding: EdgeInsets.all(4), child: Icon(Icons.download_rounded, color: Colors.white), ), ), ), if (_isDownloading) const Center(child: PlatformProgressIndicator()), ], ], ), ); // Container( // width: 80, // height: 80, // child: ActionChip( // avatar: buildIcon(), // visualDensity: VisualDensity.compact, // label: Text(widget.info.fileName, style: TextStyle(fontSize: 8)), // onPressed: download, // ), // ); Future _download() async { if (_isDownloading) { return; } setState(() { _isDownloading = true; }); try { final mimePart = await widget.message.source.fetchMessagePart( widget.message, fetchId: widget.info.fetchId, ); _mimePart = mimePart; final mediaProvider = MimeMediaProviderFactory.fromMime( widget.message.mimeMessage, mimePart, ); _mediaProvider = mediaProvider; final media = InteractiveMediaWidget( mediaProvider: mediaProvider, builder: _buildInteractiveMedia, fallbackBuilder: _buildInteractiveFallback, ); await _showAttachment(media); } on MailException catch (e) { logger.e( 'Unable to download attachment with ' 'fetch id ${widget.info.fetchId}: $e', ); if (context.mounted) { await LocalizedDialogHelper.showTextDialog( ref, ref.text.errorTitle, ref.text.attachmentDownloadError(e.message ?? e.toString()), ); } } finally { if (mounted) { setState(() { _isDownloading = false; }); } } } Future _showAttachment(InteractiveMediaWidget media) { if (_mimePart?.mediaType.sub == MediaSubtype.messageRfc822) { final mime = _mimePart?.decodeContentMessage(); if (mime != null) { final message = Message.embedded(mime, widget.message); return context.pushNamed( Routes.mailDetails, extra: message, ); } } return context.pushNamed( Routes.interactiveMedia, extra: media, ); } Widget _buildInteractiveFallback( BuildContext context, MediaProvider mediaProvider, ) { final sizeText = ref.formatMemory(mediaProvider.size); final localizations = ref.text; final iconData = IconService.instance .getForMediaType(MediaType.fromText(mediaProvider.mediaType)); return Material( child: Padding( padding: const EdgeInsets.all(32), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(8), child: Icon(iconData), ), Text( mediaProvider.name, style: Theme.of(context).textTheme.titleLarge, ), if (sizeText != null) Padding( padding: const EdgeInsets.all(8), child: Text(sizeText), ), PlatformTextButton( child: Text(localizations.attachmentActionOpen), onPressed: () => InteractiveMediaScreen.share( mediaProvider, ), ), ], ), ), ); } Widget? _buildInteractiveMedia( BuildContext context, MediaProvider mediaProvider, ) { if (mediaProvider.mediaType == 'text/calendar' || mediaProvider.mediaType == 'application/ics') { return IcalInteractiveMedia( mediaProvider: mediaProvider, message: widget.message, ); } return null; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/new_mail_message_button.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../models/compose_data.dart'; import '../routes/routes.dart'; /// Visualize a button to compose a new mail message /// /// This is done as a [FloatingActionButton] class NewMailMessageButton extends ConsumerWidget { /// Creates a [NewMailMessageButton] const NewMailMessageButton({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) => FloatingActionButton( onPressed: () => context.pushNamed( Routes.mailCompose, extra: ComposeData( null, MessageBuilder(), ComposeAction.newMessage, ), ), tooltip: ref.text.homeFabTooltip, elevation: 2, child: const Icon(Icons.add), ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/mailbox_tree.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/model.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../mail/model.dart'; import '../mail/provider.dart'; import '../settings/model.dart'; import '../settings/provider.dart'; import '../settings/theme/icon_service.dart'; /// Displays a tree of mailboxes class MailboxTree extends ConsumerWidget { /// Creates a new [MailboxTree] const MailboxTree({ super.key, required this.account, required this.onSelected, this.isReselectPossible = false, }); /// The associated account final Account account; /// Callback when a mailbox is selected final void Function(Mailbox mailbox) onSelected; /// Set to true if the user should be able to reselect the current mailbox final bool isReselectPossible; @override Widget build(BuildContext context, WidgetRef ref) { final mailboxTreeValue = ref.watch(mailboxTreeProvider(account: account)); final currentMailbox = ref.watch(currentMailboxProvider); final settings = ref.watch(settingsProvider); final localizations = ref.text; return mailboxTreeValue.when( loading: () => Center( child: PlatformCircularProgressIndicator(), ), error: (error, stacktrace) => Center(child: Text('$error')), data: (tree) { final mailboxTreeElements = tree.root.children; if (mailboxTreeElements == null) { return const SizedBox.shrink(); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ for (final element in mailboxTreeElements) _buildMailboxElement( localizations, settings, element, 0, currentMailbox, ), ], ); }, ); } Widget _buildMailboxElement( AppLocalizations localizations, Settings settings, TreeElement<Mailbox?> element, final int level, Mailbox? current, ) { final mailbox = element.value; if (mailbox == null) { return const SizedBox.shrink(); } final title = Padding( padding: EdgeInsets.only(left: level * 8.0), child: Text(mailbox.localizedName(localizations, settings)), ); final children = element.children; if (children == null) { final isCurrent = mailbox == current || (current == null && mailbox.isInbox); final iconData = IconService.instance.getForMailbox(mailbox); return SelectablePlatformListTile( leading: Icon(iconData), title: title, onTap: isCurrent && !isReselectPossible ? null : () => onSelected(mailbox), selected: isCurrent, ); } return Material( child: ExpansionTile( title: title, children: [ for (final childElement in children) _buildMailboxElement( localizations, settings, childElement, level + 1, current, ), ], ), ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/empty_message.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; class EmptyMessage extends StatelessWidget { const EmptyMessage({super.key}); @override Widget build(BuildContext context) => const Padding( padding: EdgeInsets.all(8), child: SelectablePlatformListTile( visualDensity: VisualDensity.compact, title: Text('...'), subtitle: Text('-'), ), ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/widgets.dart
export 'account_hoster_selector.dart'; export 'account_selector.dart'; export 'app_drawer.dart'; export 'attachment_chip.dart'; export 'attachment_compose_bar.dart'; export 'cupertino_status_bar.dart'; export 'editor_extensions.dart'; export 'empty_message.dart'; export 'expansion_wrap.dart'; export 'ical_composer.dart'; export 'ical_interactive_media.dart'; export 'icon_text.dart'; export 'legalese.dart'; export 'mail_address_chip.dart'; export 'mailbox_selector.dart'; export 'mailbox_tree.dart'; export 'menu_with_badge.dart'; export 'message_actions.dart'; export 'message_overview_content.dart'; export 'message_stack.dart'; export 'new_mail_message_button.dart'; export 'password_field.dart'; export 'recipient_input_field.dart'; export 'signature.dart'; export 'text_with_links.dart';
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/menu_with_badge.dart
import 'package:badges/badges.dart' as badges; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class MenuWithBadge extends StatelessWidget { const MenuWithBadge({ super.key, this.badgeContent, this.iOSText, }); final Widget? badgeContent; final String? iOSText; @override Widget build(BuildContext context) => DensePlatformIconButton( icon: badges.Badge( badgeContent: badgeContent, child: _buildIndicator(context), ), onPressed: () { if (PlatformInfo.isCupertino) { // go back context.pop(); } else { Scaffold.of(context).openDrawer(); } }, ); Widget _buildIndicator(BuildContext context) { if (PlatformInfo.isCupertino) { final iOSText = this.iOSText; return iOSText != null ? Text(iOSText) : const Icon(CupertinoIcons.back); } else { return const Icon(Icons.menu); } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/ical_interactive_media.dart
import 'dart:convert'; import 'package:collection/collection.dart' show IterableExtension; import 'package:enough_icalendar/enough_icalendar.dart'; import 'package:enough_icalendar_export/enough_icalendar_export.dart'; import 'package:enough_mail_flutter/enough_mail_flutter.dart'; import 'package:enough_mail_icalendar/enough_mail_icalendar.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/model.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../models/message.dart'; import '../scaffold_messenger/service.dart'; import '../util/localized_dialog_helper.dart'; import 'mail_address_chip.dart'; import 'text_with_links.dart'; class IcalInteractiveMedia extends StatefulHookConsumerWidget { const IcalInteractiveMedia({ super.key, required this.mediaProvider, required this.message, }); final MediaProvider mediaProvider; final Message message; @override ConsumerState<IcalInteractiveMedia> createState() => _IcalInteractiveMediaState(); } class _IcalInteractiveMediaState extends ConsumerState<IcalInteractiveMedia> { VCalendar? _calendar; VEvent? _event; bool _isPermanentError = false; bool _canReply = false; ParticipantStatus? _participantStatus; @override void initState() { super.initState(); final provider = widget.mediaProvider; try { if (provider is TextMediaProvider) { _calendar = VComponent.parse(provider.text) as VCalendar; } else if (provider is MemoryMediaProvider) { _calendar = VComponent.parse(utf8.decode(provider.data, allowMalformed: true)) as VCalendar; } _canReply = _calendar?.canReply ?? false; _event = _calendar?.event; if (_event == null) { _isPermanentError = true; } else { _participantStatus = widget.message.mimeMessage.calendarParticipantStatus; } } catch (e, s) { if (kDebugMode) { print('Unable to parse text/calendar format: $e $s'); } _isPermanentError = true; } } @override Widget build(BuildContext context) { final localizations = ref.text; final event = _calendar?.event; if (event == null) { if (_isPermanentError) { return Padding( padding: const EdgeInsets.all(8), child: Text(localizations.errorTitle), ); } return const Center(child: PlatformProgressIndicator()); } final isReply = _calendar?.method == Method.reply; final attendees = isReply ? <AttendeeProperty>[] : event.attendees; final userEmail = widget.message.account.email.toLowerCase(); final recurrenceRule = event.recurrenceRule; final end = event.end; final start = event.start; final duration = event.duration; final description = event.description; final location = event.location; final microsoftTeamsMeetingUrl = event.microsoftTeamsMeetingUrl; return Material( child: Padding( padding: const EdgeInsets.all(8), child: Column( children: [ if (isReply) Padding( padding: const EdgeInsets.all(8), child: _buildReply(context, localizations, event), ) else if (_canReply && _participantStatus == null) Row( children: [ PlatformTextButton( child: Text(localizations.actionAccept), onPressed: () => _changeParticipantStatus( ParticipantStatus.accepted, localizations, ), ), PlatformTextButton( child: PlatformText(localizations.icalendarAcceptTentatively), onPressed: () => _changeParticipantStatus( ParticipantStatus.tentative, localizations, ), ), PlatformTextButton( child: Text(localizations.actionDecline), onPressed: () => _changeParticipantStatus( ParticipantStatus.declined, localizations, ), ), ], ) else if (_participantStatus != null) Row( children: [ Padding( padding: const EdgeInsets.all(8), child: Text( _participantStatus?.localization(localizations) ?? '', ), ), PlatformTextButton( child: Text( localizations.icalendarActionChangeParticipantStatus, ), onPressed: () => _queryParticipantStatus(localizations), ), ], ), Table( columnWidths: const { 0: IntrinsicColumnWidth(), 1: FlexColumnWidth(), }, children: [ TableRow(children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelSummary), ), Padding( padding: const EdgeInsets.all(8), child: TextWithLinks( text: event.summary ?? localizations.icalendarNoSummaryInfo, ), ), ]), if (start != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelStart), ), Padding( padding: const EdgeInsets.all(8), child: Text( ref.formatDateTime( start.toLocal(), alwaysUseAbsoluteFormat: true, useLongFormat: true, ), ), ), ], ), if (end != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelEnd), ), Padding( padding: const EdgeInsets.all(8), child: Text( ref.formatDateTime( end.toLocal(), alwaysUseAbsoluteFormat: true, useLongFormat: true, ), ), ), ], ) else if (duration != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelDuration), ), Padding( padding: const EdgeInsets.all(8), child: Text( ref.formatIsoDuration(duration), ), ), ], ), if (recurrenceRule != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelRecurrenceRule), ), Padding( padding: const EdgeInsets.all(8), child: Text( recurrenceRule.toHumanReadableText( languageCode: localizations.localeName, ), ), ), ], ), if (description != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelDescription), ), Padding( padding: const EdgeInsets.all(8), child: TextWithLinks( text: description, ), ), ], ), if (location != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text( localizations.icalendarLabelLocation, ), ), Padding( padding: const EdgeInsets.all(8), child: TextWithLinks( text: location, ), ), ], ), if (microsoftTeamsMeetingUrl != null) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelTeamsUrl), ), Padding( padding: const EdgeInsets.all(8), child: TextWithLinks( text: microsoftTeamsMeetingUrl, ), ), ], ), if (attendees.isNotEmpty) TableRow( children: [ Padding( padding: const EdgeInsets.all(8), child: Text(localizations.icalendarLabelParticipants), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: attendees.map((attendee) { final isMe = attendee.email?.toLowerCase() == userEmail; final address = isMe ? widget.message.account.fromAddress : attendee.mailAddress; final participantStatus = isMe ? _participantStatus ?? attendee.participantStatus : attendee.participantStatus; final icon = participantStatus?.icon; final account = widget.message.account; final name = isMe && account is RealAccount ? account.userName ?? attendee.commonName : attendee.commonName; final textStyle = participantStatus?.textStyle; return Row( children: [ if (icon != null) Padding( padding: const EdgeInsets.all(8), child: icon, ), if (address != null) MailAddressChip(mailAddress: address) else Expanded( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (name != null) Text( name, style: textStyle, ), Padding( padding: const EdgeInsets.symmetric( vertical: 4, ), child: Text( attendee.email ?? attendee.uri.toString(), style: textStyle, ), ), ], ), ), ), ], ); }).toList(), ), ], ), ], ), if (!isReply) PlatformElevatedButton( child: Text(localizations.icalendarExportAction), onPressed: () => _exportToNativeCalendar(_calendar), ), ], ), ), ); } Future<void> _exportToNativeCalendar(VCalendar? calendar) async { if (calendar == null) { if (kDebugMode) { print('Warning: no calendar to export.'); } return; } try { await calendar.exportToNativeCalendar(); } catch (e, s) { if (kDebugMode) { print('Unable to export calendar: $e $s'); } } } Future<void> _changeParticipantStatus( ParticipantStatus status, AppLocalizations localizations, ) async { final calendar = _calendar; if (calendar == null) { return; } try { final mailClient = widget.message.source.getMimeSource(widget.message)?.mailClient; if (mailClient == null) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.icalendarParticipantStatusSentFailure( 'No mail client found.', ), ); return; } setState(() { _participantStatus = status; }); await mailClient.sendCalendarReply( calendar, status, originatingMessage: widget.message.mimeMessage, productId: 'Maily', ); ScaffoldMessengerService.instance .showTextSnackBar(localizations, status.localization(localizations)); } catch (e, s) { if (kDebugMode) { print('Unable to send status update: $e $s'); } if (context.mounted) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.icalendarParticipantStatusSentFailure( e.toString(), ), ); } } } Future<void> _queryParticipantStatus(AppLocalizations localizations) async { final status = await LocalizedDialogHelper.showTextDialog( ref, localizations.icalendarParticipantStatusChangeTitle, localizations.icalendarParticipantStatusChangeText, actions: [ PlatformTextButton( child: Text(localizations.actionAccept), onPressed: () => context.pop(ParticipantStatus.accepted), ), PlatformTextButton( child: Text(localizations.icalendarAcceptTentatively), onPressed: () => context.pop(ParticipantStatus.tentative), ), PlatformTextButton( child: Text(localizations.actionDecline), onPressed: () => context.pop(ParticipantStatus.declined), ), PlatformTextButton( child: Text(localizations.actionCancel), onPressed: () => context.pop(), ), ], ); if (status != null && status != _participantStatus) { await _changeParticipantStatus(status, localizations); } } Widget _buildReply( BuildContext context, AppLocalizations localizations, VEvent event, ) { // This is a reply from one of the participants: var attendees = event.attendees; if (attendees.isEmpty) { return Text(localizations.icalendarReplyWithoutParticipants); } final fromEmail = widget.message.mimeMessage.fromEmail; if (attendees.length > 1) { final attendee = attendees.firstWhereOrNull((a) => a.email == fromEmail); if (attendee != null) { attendees = [attendee]; } } // This should be the most common situation: final attendee = attendees.first; final status = attendee.participantStatus; if (status == null) { return Text(localizations .icalendarReplyWithoutStatus(attendee.mailAddress.toString())); } return Text( status.participantReplyText( localizations, attendee.mailAddress.toString(), ), style: const TextStyle(fontStyle: FontStyle.italic), ); } } extension ExtensionParticipantStatusTextStyle on ParticipantStatus { // static const TextStyle _styleAccepted = // const TextStyle(color: Colors.green); static const TextStyle _styleDeclined = TextStyle(color: Colors.red, decorationStyle: TextDecorationStyle.dashed); static const TextStyle _styleTentative = TextStyle(fontStyle: FontStyle.italic); TextStyle? get textStyle { switch (this) { case ParticipantStatus.needsAction: return null; case ParticipantStatus.accepted: return null; //_styleAccepted; case ParticipantStatus.declined: return _styleDeclined; case ParticipantStatus.tentative: return _styleTentative; case ParticipantStatus.delegated: return null; case ParticipantStatus.inProcess: return null; case ParticipantStatus.partial: return null; case ParticipantStatus.completed: return null; case ParticipantStatus.other: return null; } } Icon? get icon { switch (this) { case ParticipantStatus.needsAction: return null; case ParticipantStatus.accepted: return Icon( CommonPlatformIcons.ok, color: Colors.green, ); case ParticipantStatus.declined: return Icon(CommonPlatformIcons.cancel); case ParticipantStatus.tentative: return Icon(PlatformInfo.isCupertino ? CupertinoIcons.question : Icons.question_answer); case ParticipantStatus.delegated: return null; case ParticipantStatus.inProcess: return null; case ParticipantStatus.partial: return null; case ParticipantStatus.completed: return null; case ParticipantStatus.other: return null; } } String localization(AppLocalizations localizations) { switch (this) { case ParticipantStatus.needsAction: return localizations.icalendarParticipantStatusNeedsAction; case ParticipantStatus.accepted: return localizations.icalendarParticipantStatusAccepted; case ParticipantStatus.declined: return localizations.icalendarParticipantStatusDeclined; case ParticipantStatus.tentative: return localizations.icalendarParticipantStatusAcceptedTentatively; case ParticipantStatus.delegated: return localizations.icalendarParticipantStatusDelegated; case ParticipantStatus.inProcess: return localizations.icalendarParticipantStatusInProcess; case ParticipantStatus.partial: return localizations.icalendarParticipantStatusPartial; case ParticipantStatus.completed: return localizations.icalendarParticipantStatusCompleted; case ParticipantStatus.other: return localizations.icalendarParticipantStatusOther; } } String participantReplyText(AppLocalizations localizations, String attendee) { switch (this) { case ParticipantStatus.needsAction: return localizations.icalendarReplyStatusNeedsAction(attendee); case ParticipantStatus.accepted: return localizations.icalendarReplyStatusAccepted(attendee); case ParticipantStatus.declined: return localizations.icalendarReplyStatusDeclined(attendee); case ParticipantStatus.tentative: return localizations.icalendarReplyStatusAcceptedTentatively(attendee); case ParticipantStatus.delegated: return localizations.icalendarReplyStatusDelegated(attendee); case ParticipantStatus.inProcess: return localizations.icalendarReplyStatusInProcess(attendee); case ParticipantStatus.partial: return localizations.icalendarReplyStatusPartial(attendee); case ParticipantStatus.completed: return localizations.icalendarReplyStatusCompleted(attendee); case ParticipantStatus.other: return localizations.icalendarReplyStatusOther(attendee); } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/account_hoster_selector.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../hoster/service.dart'; import '../localization/extension.dart'; /// Allows to select a mail hoster class MailHosterSelector extends ConsumerWidget { /// Creates a [MailHosterSelector] const MailHosterSelector({super.key, required this.onSelected}); /// Called when a mail hoster has been selected final void Function(MailHoster? hoster) onSelected; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final hosters = MailHosterService.instance.hosters; return ListView.separated( itemBuilder: (context, index) { if (index == 0) { return Center( child: PlatformTextButton( child: Text(localizations.accountProviderCustom), onPressed: () => onSelected(null), ), ); } final provider = hosters[index - 1]; return Center( child: provider.buildSignInButton( ref, onPressed: () => onSelected(provider), ), ); }, separatorBuilder: (context, index) => const Divider(), itemCount: hosters.length + 1, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/legalese.dart
import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import 'text_with_links.dart'; class Legalese extends ConsumerWidget { const Legalese({super.key}); static const String urlPrivacyPolicy = 'https://www.enough.de/privacypolicy/maily-pp.html'; static const String urlTermsAndConditions = 'https://github.com/Enough-Software/enough_mail_app/blob/main/LICENSE'; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final legaleseUsage = localizations.legaleseUsage; final privacyPolicy = localizations.legalesePrivacyPolicy; final termsAndConditions = localizations.legaleseTermsAndConditions; final ppIndex = legaleseUsage.indexOf('[PP]'); final tcIndex = legaleseUsage.indexOf('[TC]'); final legaleseParts = [ TextLink(legaleseUsage.substring(0, ppIndex)), TextLink(privacyPolicy, urlPrivacyPolicy), TextLink(legaleseUsage.substring(ppIndex + '[PP]'.length, tcIndex)), TextLink(termsAndConditions, urlTermsAndConditions), TextLink(legaleseUsage.substring(tcIndex + '[TC]'.length)), ]; return TextWithNamedLinks( parts: legaleseParts, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/app_drawer.dart
import 'package:badges/badges.dart' as badges; import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../account/model.dart'; import '../account/provider.dart'; import '../extensions/extension_action_tile.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../routes/routes.dart'; import '../settings/theme/icon_service.dart'; import '../util/localized_dialog_helper.dart'; import 'mailbox_tree.dart'; /// Displays the base navigation drawer with all accounts class AppDrawer extends ConsumerWidget { /// Creates a new [AppDrawer] const AppDrawer({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final accounts = ref.watch(allAccountsProvider); final theme = Theme.of(context); final localizations = ref.text; final iconService = IconService.instance; final currentAccount = ref.watch(currentAccountProvider); final hasAccountsWithErrors = ref.watch(hasAccountWithErrorProvider); return PlatformDrawer( child: SafeArea( child: Column( children: [ Material( elevation: 18, child: Padding( padding: const EdgeInsets.all(8), child: _buildAccountHeader( context, currentAccount, accounts, theme, ), ), ), Expanded( child: SingleChildScrollView( child: Material( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildAccountSelection( context, accounts, currentAccount, localizations, hasAccountsWithErrors: hasAccountsWithErrors, ), _buildFolderTree(context, currentAccount), if (currentAccount is RealAccount) ExtensionActionTile.buildSideMenuForAccount( context, currentAccount, ), const Divider(), PlatformListTile( leading: Icon(iconService.about), title: Text(localizations.drawerEntryAbout), onTap: () { LocalizedDialogHelper.showAbout( ref, ); }, ), ], ), ), ), ), Material( elevation: 18, child: PlatformListTile( leading: Icon(iconService.settings), title: Text(localizations.drawerEntrySettings), onTap: () { context.pushNamed(Routes.settings); }, ), ), ], ), ), ); } Widget _buildAccountHeader( BuildContext context, Account? currentAccount, List<Account> accounts, ThemeData theme, ) { if (currentAccount == null) { return const SizedBox.shrink(); } final avatarAccount = currentAccount is RealAccount ? currentAccount : (currentAccount is UnifiedAccount ? currentAccount.accounts.first : accounts.firstWhereOrNull((a) => a is RealAccount) as RealAccount?); final avatarImageUrl = avatarAccount?.imageUrlGravatar; final hasError = currentAccount is RealAccount && currentAccount.hasError; final userName = currentAccount is RealAccount ? currentAccount.userName : null; final accountName = Text( currentAccount.name, style: const TextStyle(fontWeight: FontWeight.bold), ); final accountNameWithBadge = hasError ? badges.Badge(child: accountName) : accountName; return PlatformListTile( onTap: () { if (currentAccount is UnifiedAccount) { context.pushNamed(Routes.settingsAccounts); } else { context.pushNamed( Routes.accountEdit, pathParameters: { Routes.pathParameterEmail: currentAccount.email, }, ); } }, title: avatarAccount == null ? const SizedBox.shrink() : Row( children: [ CircleAvatar( backgroundColor: theme.secondaryHeaderColor, backgroundImage: avatarImageUrl == null ? null : NetworkImage(avatarImageUrl), radius: 30, ), const Padding( padding: EdgeInsets.only(left: 8), ), Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ accountNameWithBadge, if (userName != null) Text( userName, style: const TextStyle( fontStyle: FontStyle.italic, fontSize: 14, ), ), Text( currentAccount is UnifiedAccount ? currentAccount.accounts .map((a) => a.name) .join(', ') : currentAccount.email, style: const TextStyle( fontStyle: FontStyle.italic, fontSize: 14, ), ), ], ), ), ], ), ); } Widget _buildAccountSelection( BuildContext context, List<Account> accounts, Account? currentAccount, AppLocalizations localizations, { required bool hasAccountsWithErrors, }) => accounts.length > 1 ? ExpansionTile( leading: hasAccountsWithErrors ? const Badge() : null, title: Text( localizations.drawerAccountsSectionTitle(accounts.length), ), children: [ for (final account in accounts) _SelectableAccountTile( account: account, currentAccount: currentAccount, ), _buildAddAccountTile(context, localizations), ], ) : _buildAddAccountTile(context, localizations); Widget _buildAddAccountTile( BuildContext context, AppLocalizations localizations, ) => PlatformListTile( leading: const Icon(Icons.add), title: Text(localizations.drawerEntryAddAccount), onTap: () { if (!useAppDrawerAsRoot) { context.pop(); } context.pushNamed(Routes.accountAdd); }, ); Widget _buildFolderTree( BuildContext context, Account? account, ) { if (account == null) { return const SizedBox.shrink(); } return MailboxTree( account: account, onSelected: (mailbox) => _navigateToMailbox(context, account, mailbox), isReselectPossible: true, ); } void _navigateToMailbox( BuildContext context, Account account, Mailbox mailbox, ) { if (!useAppDrawerAsRoot) { while (context.canPop()) { context.pop(); } } if (mailbox.isInbox) { context.goNamed( Routes.mailForAccount, pathParameters: { Routes.pathParameterEmail: account.email, }, ); } else { context.pushNamed( Routes.mailForMailbox, pathParameters: { Routes.pathParameterEmail: account.email, Routes.pathParameterEncodedMailboxPath: mailbox.encodedPath, }, ); } } } class _SelectableAccountTile extends ConsumerWidget { const _SelectableAccountTile({ required this.account, required this.currentAccount, }); final Account account; final Account? currentAccount; @override Widget build(BuildContext context, WidgetRef ref) { final account = this.account; final hasError = account is RealAccount && account.hasError; final localizations = ref.text; return SelectablePlatformListTile( leading: hasError ? const Icon(Icons.error_outline) : null, tileColor: hasError ? Colors.red : null, title: Text( account is UnifiedAccount ? localizations.unifiedAccountName : account.name, ), selected: account == currentAccount, onTap: () { if (!useAppDrawerAsRoot) { context.pop(); } if (hasError) { context.pushNamed( Routes.accountEdit, pathParameters: { Routes.pathParameterEmail: account.email, }, ); } else { context.goNamed( Routes.mailForAccount, pathParameters: { Routes.pathParameterEmail: account.email, }, ); } }, onLongPress: () { if (account is UnifiedAccount) { context.pushNamed( Routes.settingsAccounts, pathParameters: { Routes.pathParameterEmail: account.email, }, ); } else { context.pushNamed( Routes.accountEdit, pathParameters: { Routes.pathParameterEmail: account.email, }, ); } }, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/mail_address_chip.dart
import 'dart:async'; import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../models/compose_data.dart'; import '../routes/routes.dart'; import '../scaffold_messenger/service.dart'; import 'icon_text.dart'; class MailAddressChip extends ConsumerWidget { const MailAddressChip({super.key, required this.mailAddress, this.icon}); final MailAddress mailAddress; final Widget? icon; String get nameOrEmail => (mailAddress.hasPersonalName) ? mailAddress.personalName ?? mailAddress.email : mailAddress.email; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final theme = Theme.of(context); return PlatformPopupMenuButton<_AddressAction>( cupertinoButtonPadding: EdgeInsets.zero, icon: icon, title: mailAddress.hasPersonalName ? Text(nameOrEmail) : null, message: Text(mailAddress.email, style: theme.textTheme.bodySmall), itemBuilder: (context) => [ PlatformPopupMenuItem( value: _AddressAction.copy, child: IconText( icon: Icon(CommonPlatformIcons.copy), label: Text(localizations.actionAddressCopy), ), ), PlatformPopupMenuItem( value: _AddressAction.compose, child: IconText( icon: Icon(CommonPlatformIcons.add), label: Text(localizations.actionAddressCompose), ), ), PlatformPopupMenuItem( value: _AddressAction.search, child: IconText( icon: const Icon(Icons.search), label: Text(localizations.actionAddressSearch), ), ), ], onSelected: (value) async { switch (value) { case _AddressAction.none: break; case _AddressAction.copy: await Clipboard.setData(ClipboardData(text: mailAddress.email)); ScaffoldMessengerService.instance.showTextSnackBar( localizations, localizations.feedbackResultInfoCopied, ); break; case _AddressAction.compose: final messageBuilder = MessageBuilder()..to = [mailAddress]; final composeData = ComposeData(null, messageBuilder, ComposeAction.newMessage); if (context.mounted) { unawaited( context.pushNamed(Routes.mailCompose, extra: composeData), ); } break; case _AddressAction.search: final search = MailSearch( mailAddress.email, SearchQueryType.fromOrTo, ); if (context.mounted) { unawaited( context.pushNamed(Routes.mailSearch, extra: search), ); } break; } }, child: PlatformChip(label: Text(nameOrEmail)), ); } } enum _AddressAction { none, copy, compose, search }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/search_text_field.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/cupertino.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../models/message_source.dart'; import '../routes/routes.dart'; /// A dedicated search field optimized for Cupertino class CupertinoSearch extends ConsumerWidget { /// Creates a new [CupertinoSearch] const CupertinoSearch({super.key, required this.messageSource}); /// The source in which should be searched final MessageSource messageSource; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; return CupertinoSearchFlowTextField( onSubmitted: (text) => _onSearchSubmitted(ref, text.trim()), cancelText: localizations.actionCancel, ); } void _onSearchSubmitted(WidgetRef ref, String text) { if (text.isEmpty) { return; } final search = MailSearch(text, SearchQueryType.allTextHeaders); final next = messageSource.search(ref.text, search); ref.context.pushNamed( Routes.messageSource, pathParameters: { Routes.pathParameterEmail: messageSource.account.email, }, extra: next, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/recipient_input_field.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttercontactpicker/fluttercontactpicker.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../app_lifecycle/provider.dart'; import '../contact/model.dart'; import '../localization/extension.dart'; import '../logger.dart'; import '../util/validator.dart'; import 'icon_text.dart'; /// Allows to enter recipients for a message class RecipientInputField extends StatefulHookConsumerWidget { /// Creates a new [RecipientInputField] const RecipientInputField({ super.key, this.labelText, this.hintText, this.controller, this.additionalSuffixIcon, this.autofocus = false, required this.addresses, required this.contactManager, }); /// Optional label text final String? labelText; /// Optional hint text final String? hintText; /// Optional controller final TextEditingController? controller; /// Optional additional suffix icon final Widget? additionalSuffixIcon; /// Should the field be focused on first build? /// /// Defaults to `false` final bool autofocus; /// The list of addresses final List<MailAddress> addresses; /// The optional contact manager final ContactManager? contactManager; @override ConsumerState<RecipientInputField> createState() => _RecipientInputFieldState(); } enum _AddressAction { copy, } class _RecipientInputFieldState extends ConsumerState<RecipientInputField> { final _focusNode = FocusNode(); late TextEditingController _controller; @override void initState() { _controller = widget.controller ?? TextEditingController(); super.initState(); _focusNode.addListener(_update); } void _update() { if (!_focusNode.hasFocus) { checkEmail(_controller.text); } setState(() {}); } @override void dispose() { super.dispose(); _focusNode.dispose(); _controller.dispose(); } @override Widget build(BuildContext context) { final theme = Theme.of(context); final localizations = ref.text; return DragTarget<MailAddress>( builder: (context, candidateData, rejectedData) { final labelText = widget.labelText; return Container( color: candidateData.isEmpty ? null : theme.hoverColor, child: Wrap( children: [ if (widget.addresses.isNotEmpty && labelText != null) Padding( padding: const EdgeInsets.only(top: 8, right: 8), child: Text( labelText, style: TextStyle( color: _focusNode.hasFocus ? theme.colorScheme.secondary : theme.hintColor, ), ), ), for (final address in widget.addresses) Draggable( data: address, feedback: Opacity( opacity: 0.8, child: Material( child: _AddressChip( address: address, ), ), ), feedbackOffset: const Offset(10, 10), childWhenDragging: Opacity( opacity: 0.6, child: _AddressChip( address: address, ), ), child: _AddressChip<_AddressAction>( address: address, onDeleted: () { widget.addresses.remove(address); setState(() {}); }, menuItems: [ PlatformPopupMenuItem( value: _AddressAction.copy, child: IconText( icon: Icon(CommonPlatformIcons.copy), label: Text(localizations.actionAddressCopy), ), ), ], onMenuItemSelected: (action) { switch (action) { case _AddressAction.copy: Clipboard.setData(ClipboardData(text: address.email)); break; } }, ), ), buildInput(theme, context), ], ), ); }, onAccept: (mailAddress) { if (!widget.addresses.contains(mailAddress)) { widget.addresses.add(mailAddress); } }, onLeave: (mailAddress) { widget.addresses.remove(mailAddress); }, ); } Widget buildInput(ThemeData theme, BuildContext context) => RawAutocomplete<MailAddress>( focusNode: _focusNode, textEditingController: _controller, optionsBuilder: (textEditingValue) { final search = textEditingValue.text.toLowerCase(); if (search.length < 2) { return []; } if (search.endsWith(' ') || search.endsWith(';') || search.endsWith(';')) { // check if this is a complete email address final email = textEditingValue.text.substring(0, search.length - 1); checkEmail(email); } final contactManager = widget.contactManager; if (contactManager == null) { return []; } final matches = contactManager.find(search).toList(); // do not suggest recipients that are already added: widget.addresses.forEach(matches.remove); return matches; }, displayStringForOption: (option) => option.toString(), fieldViewBuilder: (context, textEditingController, focusNode, onFieldSubmitted) => DecoratedPlatformTextField( controller: textEditingController, focusNode: focusNode, autofocus: widget.autofocus, onSubmitted: (text) { onFieldSubmitted(); }, onEditingComplete: () => checkEmail(_controller.text), keyboardType: TextInputType.emailAddress, decoration: InputDecoration( labelText: widget.addresses.isNotEmpty ? null : widget.labelText, hintText: widget.hintText, suffixIcon: widget.additionalSuffixIcon == null ? PlatformIconButton( icon: const Icon(Icons.contacts), onPressed: () => _pickContact(textEditingController), ) : Row( mainAxisSize: MainAxisSize.min, children: [ widget.additionalSuffixIcon ?? const SizedBox.shrink(), PlatformIconButton( icon: const Icon(Icons.contacts), onPressed: () => _pickContact(textEditingController), ), ], ), ), ), optionsViewBuilder: (context, onSelected, options) => Material( child: Align( alignment: Alignment.topLeft, child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 200), child: ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(8), itemCount: options.length, itemBuilder: (BuildContext context, int index) { final MailAddress option = options.elementAt(index); return PlatformActionChip( label: Column( children: [ if (option.hasPersonalName) Text( option.personalName ?? '', ), Text(option.email, style: theme.textTheme.bodySmall), ], ), onPressed: () { final currentTextInput = _controller.text; onSelected(option); if (!widget.addresses.contains(option)) { widget.addresses.add(option); setState(() {}); _controller.text = ''; } else { _controller.value = TextEditingValue( selection: TextSelection.collapsed( offset: currentTextInput.length, ), text: currentTextInput, ); } }, ); }, ), ), ), ), ); void checkEmail(String input) { if (Validator.validateEmail(input)) { final address = MailAddress(null, input); widget.addresses.add(address); _controller.text = ''; setState(() {}); } } Future<void> _pickContact(TextEditingController controller) async { try { ref .read(appLifecycleProvider.notifier) .ignoreNextInactivationCycle(timeout: const Duration(seconds: 120)); final contact = await FlutterContactPicker.pickEmailContact(); final email = contact.email?.email; if (email != null) { widget.addresses.add( MailAddress( contact.fullName, email, ), ); } setState(() {}); } catch (e, s) { logger.e('Unable to pick contact $e', error: e, stackTrace: s); } } } class _AddressChip<T> extends StatelessWidget { const _AddressChip({ super.key, required this.address, this.onDeleted, this.menuItems, this.onMenuItemSelected, }); final MailAddress address; final VoidCallback? onDeleted; /// Compare [onMenuItemSelected] final List<PlatformPopupMenuItem<T>>? menuItems; /// Compare [menuItems] final void Function(T value)? onMenuItemSelected; @override Widget build(BuildContext context) { final content = PlatformChip( label: Column( children: [ Text(address.personalName ?? ''), Text(address.email, style: Theme.of(context).textTheme.bodySmall), ], ), deleteIcon: const Icon(Icons.close), onDeleted: onDeleted, ); final menuItems = this.menuItems; if (menuItems == null) { return content; } final theme = Theme.of(context); return PlatformPopupMenuButton<T>( cupertinoButtonPadding: EdgeInsets.zero, title: address.hasPersonalName ? Text(address.personalName ?? '') : null, message: Text(address.email, style: theme.textTheme.bodySmall), itemBuilder: (context) => menuItems, onSelected: onMenuItemSelected, child: content, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/message_overview_content.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../models/message.dart'; import '../settings/theme/icon_service.dart'; /// Displays the content of a message in the message overview. class MessageOverviewContent extends ConsumerWidget { /// Creates a new [MessageOverviewContent] widget. const MessageOverviewContent({ super.key, required this.message, required this.isSentMessage, }); /// The message to display. final Message message; /// Whether the message is a sent message. final bool isSentMessage; @override Widget build(BuildContext context, WidgetRef ref) { final msg = message; final mime = msg.mimeMessage; final localizations = ref.text; final threadSequence = mime.threadSequence; final threadLength = threadSequence != null ? threadSequence.toList().length : 0; final subject = mime.decodeSubject() ?? localizations.subjectUndefined; final senderOrRecipients = _getSenderOrRecipients(mime, localizations); final hasAttachments = msg.hasAttachment; final date = ref.formatDateTime(mime.decodeDate()); final theme = Theme.of(context); return Container( padding: const EdgeInsets.symmetric(vertical: 4), color: msg.isFlagged ? theme.colorScheme.secondary : null, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ Expanded( child: Padding( padding: const EdgeInsets.only(right: 8), child: Text( senderOrRecipients, overflow: TextOverflow.fade, softWrap: false, style: TextStyle( fontWeight: msg.isSeen ? FontWeight.normal : FontWeight.bold, ), ), ), ), Text(date, style: const TextStyle(fontSize: 12)), if (hasAttachments || msg.isAnswered || msg.isForwarded || msg.isFlagged || threadLength != 0) Padding( padding: const EdgeInsets.only(left: 8), child: Row( children: [ if (msg.isFlagged) const Icon(Icons.outlined_flag, size: 12), if (hasAttachments) const Icon(Icons.attach_file, size: 12), if (msg.isAnswered) const Icon(Icons.reply, size: 12), if (msg.isForwarded) const Icon(Icons.forward, size: 12), if (threadLength != 0) IconService.buildNumericIcon( context, threadLength, size: 12, ), ], ), ), ], ), Text( subject, overflow: TextOverflow.ellipsis, style: TextStyle( fontStyle: FontStyle.italic, fontWeight: msg.isSeen ? FontWeight.normal : FontWeight.bold, ), ), ], ), ); } String _getSenderOrRecipients( MimeMessage mime, AppLocalizations localizations, ) { if (isSentMessage) { return mime.recipients .map((r) => r.hasPersonalName ? r.personalName : r.email) .join(', '); } MailAddress? from; from = (mime.from?.isNotEmpty ?? false) ? mime.from?.first : mime.sender; return (from?.personalName?.isNotEmpty ?? false) ? from?.personalName ?? '' : from?.email ?? localizations.emailSenderUnknown; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/widgets/expansion_wrap.dart
// ignore_for_file: avoid_setters_without_getters import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; /// The position of the indicator. enum ExpansionWrapIndicatorPosition { /// The indicator is placed at the end of the last visible line. inline, /// The indicator is placed at the end of the last visible line, but /// aligned to the right border of the widget. border, } /// A widget that displays its children in a wrap layout and adds an indicator /// at the end if the children do not fit in the available space. class ExpansionWrap extends RenderObjectWidget { /// Creates a new [ExpansionWrap] widget. const ExpansionWrap({ super.key, required this.children, required this.expandIndicator, required this.maxRuns, required this.compressIndicator, this.isExpanded = false, this.spacing = 0.0, this.runSpacing = 0.0, this.indicatorPosition = ExpansionWrapIndicatorPosition.border, }); /// The children to display. final List<Widget> children; /// The widget to display when the children are compressed. final Widget expandIndicator; /// The widget to display when the children are expanded. final Widget compressIndicator; /// The maximum number of lines to display. final int? maxRuns; /// The spacing between the children. final double spacing; /// The spacing between the lines. final double runSpacing; /// Whether the children are expanded. final bool isExpanded; /// The position of the indicator. final ExpansionWrapIndicatorPosition indicatorPosition; @override RenderObjectElement createElement() => _ExpansionWrapElement(this); @override RenderObject createRenderObject(BuildContext context) => RenderExpansionWrap( maxRuns: maxRuns, spacing: spacing, runSpacing: runSpacing, isExpanded: isExpanded, indicatorPosition: indicatorPosition, ); @override void updateRenderObject( BuildContext context, covariant RenderExpansionWrap renderObject, ) { // print('widget.updateRenderObject'); super.updateRenderObject(context, renderObject); renderObject ..maxRuns = maxRuns ..spacing = spacing ..runSpacing = runSpacing ..isExpanded = isExpanded ..indicatorPosition = indicatorPosition; } } class _ExpansionWrapElement extends RenderObjectElement { _ExpansionWrapElement(ExpansionWrap super.widget); static const int _expandIndicatorSlot = -1; static const int _compressIndicatorSlot = -2; Element? _expandIndicator; Element? _compressIndicator; List<Element>? _children; @override ExpansionWrap get widget => super.widget as ExpansionWrap; @override RenderExpansionWrap get renderObject => super.renderObject as RenderExpansionWrap; @override void visitChildren(ElementVisitor visitor) { final expandIndicator = _expandIndicator; if (expandIndicator != null) visitor(expandIndicator); final compressIndicator = _compressIndicator; if (compressIndicator != null) visitor(compressIndicator); final children = _children; if (children != null) { children.forEach(visitor); } } Element? _getChild(int slot) { if (slot == _expandIndicatorSlot) { return _expandIndicator; } else if (slot == _compressIndicatorSlot) { return _compressIndicator; } else { final children = _children; if (children != null && slot < children.length && slot >= 0) { return children[slot]; } } return null; } void _setChild(int slot, Element? value) { if (slot == _expandIndicatorSlot) { _expandIndicator = value; } else if (slot == _compressIndicatorSlot) { _compressIndicator = value; } else { final children = _children; if (children != null) { if (slot < children.length && slot >= 0) { if (value != null) { children[slot] = value; } else { children.removeAt(slot); } } else if (value != null) { children.add(value); } } else if (value != null) { _children = [value]; } } } @override void forgetChild(Element child) { final slot = child.slot; // print('element.forgetChild at $slot'); if (slot is int) { if (slot == _expandIndicatorSlot) { _expandIndicator = null; } else if (slot == _compressIndicatorSlot) { _compressIndicator = null; } else { final children = _children; if (children != null && slot < children.length && slot >= 0) { children.removeAt(slot); } } } super.forgetChild(child); } void _mountChild(Widget? widget, int slot) { final Element? oldChild = _getChild(slot); final Element? newChild = updateChild(oldChild, widget, slot); _setChild(slot, newChild); } @override void mount(Element? parent, dynamic newSlot) { // print('element.mount at $newSlot'); super.mount(parent, newSlot); _mountChild(widget.expandIndicator, _expandIndicatorSlot); _mountChild(widget.compressIndicator, _compressIndicatorSlot); final widgets = widget.children; for (var i = 0; i < widgets.length; i++) { _mountChild(widgets[i], i); } } void _updateChild(Widget? widget, int slot) { final Element? oldChild = _getChild(slot); final Element? newChild = updateChild(oldChild, widget, slot); _setChild(slot, newChild); } @override void update(ExpansionWrap newWidget) { // print('element.update'); super.update(newWidget); assert(widget == newWidget); _updateChild(widget.expandIndicator, _expandIndicatorSlot); _updateChild(widget.compressIndicator, _compressIndicatorSlot); final widgets = widget.children; for (var i = 0; i < widgets.length; i++) { _updateChild(widgets[i], i); } // TODO(RV): remove other children widgets? } void _updateRenderObject(RenderBox? child, int? slot) { if (slot == _expandIndicatorSlot) { renderObject.expandIndicator = child; } else if (slot == _compressIndicatorSlot) { renderObject.compressIndicator = child; } else if (slot != null && child != null) { renderObject.addWrapChild(child); } } @override void insertRenderObjectChild(RenderObject child, dynamic slot) { // print('element.insertRenderObjectChild at slot $slot'); assert(child is RenderBox); assert(slot is int); _updateRenderObject(child as RenderBox, slot); } @override void removeRenderObjectChild(RenderObject child, dynamic slot) { // print('element.removeRenderObjectChild at $slot'); assert(child is RenderBox); _updateRenderObject(null, slot); } @override void moveRenderObjectChild( covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot, ) { // TODO(RV): implement moveRenderObjectChild _updateRenderObject(child as RenderBox, 0); } } class _WrapParentData extends BoxParentData { bool _isVisible = true; } extension _WrapParentDataExtension on ParentData? { set isVisible(bool value) { final data = this; if (data is _WrapParentData) { data._isVisible = value; } } _WrapParentData toWrapParentData() { final data = this; if (data is _WrapParentData) return data; throw Exception('ParentData $data is not a _WrapParentData'); } } /// Renders the children in a wrap layout and adds an indicator at the end if /// the children do not fit in the available space. class RenderExpansionWrap extends RenderBox { /// Creates a new [RenderExpansionWrap] widget. RenderExpansionWrap({ required int? maxRuns, required double spacing, required runSpacing, required bool isExpanded, required ExpansionWrapIndicatorPosition indicatorPosition, }) : _maxRuns = maxRuns, _spacing = spacing, _runSpacing = runSpacing, _isExpanded = isExpanded, _indicatorPosition = indicatorPosition; int? _maxRuns; set maxRuns(int? value) { if (value == _maxRuns) return; _maxRuns = value; markNeedsLayout(); } double _spacing; set spacing(double value) { if (value == _spacing) return; _spacing = value; markNeedsLayout(); } double _runSpacing; set runSpacing(double value) { if (value == _runSpacing) return; _runSpacing = value; markNeedsLayout(); } bool _isExpanded; set isExpanded(bool value) { if (value == _isExpanded) return; _isExpanded = value; markNeedsLayout(); } RenderBox? _expandIndicator; set expandIndicator(RenderBox? value) { if (value == _expandIndicator) return; _updateChild(_expandIndicator, value); _expandIndicator = value; markNeedsLayout(); } RenderBox? _compressIndicator; set compressIndicator(RenderBox? value) { if (value == _compressIndicator) return; _updateChild(_compressIndicator, value); _compressIndicator = value; markNeedsLayout(); } ExpansionWrapIndicatorPosition _indicatorPosition = ExpansionWrapIndicatorPosition.border; set indicatorPosition(ExpansionWrapIndicatorPosition value) { if (value == _indicatorPosition) return; _indicatorPosition = value; markNeedsLayout(); } List<RenderBox>? _wrapChildren; /// Adds a child to the end of the children list. void addWrapChild(RenderBox child) { adoptChild(child); _wrapChildren ??= []; _wrapChildren?.add(child); } /// Removes all children from the list. void clearWrapChildren() { final children = _wrapChildren; if (children != null) { children.forEach(dropChild); _wrapChildren = null; } } void _updateChild(RenderBox? oldChild, RenderBox? newChild) { if (oldChild != null) { dropChild(oldChild); } if (newChild != null) { adoptChild(newChild); } } // The returned list is ordered for hit testing. Iterable<RenderBox> get _allChildren sync* { final expandIndicator = _expandIndicator; if (expandIndicator != null) yield expandIndicator; final compressIndicator = _compressIndicator; if (compressIndicator != null) yield compressIndicator; final children = _wrapChildren; if (children != null) { for (final child in children) { yield child; } } } @override void attach(PipelineOwner owner) { // print('attach'); super.attach(owner); for (final RenderBox child in _allChildren) { child.attach(owner); } } @override void detach() { // print('detach'); super.detach(); for (final RenderBox child in _allChildren) { child.detach(); } } @override void redepthChildren() { _allChildren.forEach(redepthChild); } @override void visitChildren(RenderObjectVisitor visitor) { _allChildren.forEach(visitor); } @override List<DiagnosticsNode> debugDescribeChildren() { final List<DiagnosticsNode> value = <DiagnosticsNode>[]; void addDiagnostic(RenderBox? child, String name) { if (child != null) value.add(child.toDiagnosticsNode(name: name)); } addDiagnostic(_expandIndicator, 'expandIndicator'); addDiagnostic(_compressIndicator, 'compressIndicator'); final children = _wrapChildren; if (children != null) { for (var i = 0; i < children.length; i++) { final child = children[i]; addDiagnostic(child, 'child $i'); } } return value; } @override bool get sizedByParent => false; @override double computeMinIntrinsicWidth(double height) { var min = 0.0; for (final child in _allChildren) { final minIntrinsic = child.getMinIntrinsicWidth(height); if (minIntrinsic > min) { min = minIntrinsic; } } return min; } @override double computeMaxIntrinsicWidth(double height) { var max = 0.0; var addSpacing = false; for (final child in _allChildren) { if (addSpacing) { max += _spacing; } max += child.getMaxIntrinsicWidth(height); addSpacing = true; } return max; } @override double computeMinIntrinsicHeight(double width) { var min = 0.0; for (final child in _allChildren) { final minIntrinsic = child.getMinIntrinsicHeight(width); if (minIntrinsic > min) { min = minIntrinsic; } } return min; } @override double computeMaxIntrinsicHeight(double width) => computeMinIntrinsicHeight(width); @override double computeDistanceToActualBaseline(TextBaseline baseline) { assert(_wrapChildren != null); final first = _wrapChildren?.first; final parentData = first?.parentData; if (first != null && parentData is BoxParentData) { return parentData.offset.dy + (first.getDistanceToActualBaseline(baseline) ?? 0); } return 0; } static Size _layoutBox(RenderBox? box, BoxConstraints constraints) { if (box == null) return Size.zero; box.layout(constraints, parentUsesSize: true); return box.size; } @override void setupParentData(covariant RenderObject child) { child.parentData = _WrapParentData(); } // All of the dimensions below were taken from the Material Design spec: // https://material.io/design/components/lists.html#specs @override void performLayout() { final BoxConstraints constraints = this.constraints; final BoxConstraints looseConstraints = constraints.loosen(); final double availableWidth = looseConstraints.maxWidth; final children = _wrapChildren; final expanded = _isExpanded; final expandIndicator = _expandIndicator; final compressIndicator = _compressIndicator; if (expanded) { if (expandIndicator != null) { expandIndicator.parentData.isVisible = false; } } else if (compressIndicator != null) { compressIndicator.parentData.isVisible = false; } final spacing = _spacing; final runSpacing = _runSpacing; final compressIndicatorSize = _layoutBox(compressIndicator, looseConstraints); final expandIndicatorSize = _layoutBox(expandIndicator, looseConstraints); final indicator = expanded ? compressIndicator : expandIndicator; final indicatorSize = expanded ? compressIndicatorSize : expandIndicatorSize; final indicatorWith = indicatorSize.width; final originalMaxRuns = _maxRuns ?? double.maxFinite.floor(); final maxRuns = expanded ? double.maxFinite.floor() : originalMaxRuns; var currentRunWidth = 0.0; var currentRunHeight = 0.0; var currentRunY = 0.0; var maxRunWidth = 0.0; var currentRun = 1; var currentRunNumberOfChildren = 0; double? crossAxisMaxInCompressedState; if (children != null) { final lastChildIndex = children.length - 1; for (var i = 0; i <= lastChildIndex; i++) { final child = children[i]; final childSize = _layoutBox(child, looseConstraints); final parentData = child.parentData.toWrapParentData() .._isVisible = currentRun <= maxRuns; if (currentRunNumberOfChildren > 0 && ((currentRunWidth + childSize.width > availableWidth) || (currentRun == maxRuns && (currentRunWidth + childSize.width + spacing + indicatorWith > availableWidth)) || (i == lastChildIndex && (currentRunWidth + childSize.width + spacing + indicatorWith > availableWidth)))) { // line break: move current child to next row: if (currentRun == maxRuns && currentRunWidth + spacing + indicatorWith > maxRunWidth) { maxRunWidth = currentRunWidth + spacing + indicatorWith; } else if (currentRunWidth > maxRunWidth) { maxRunWidth = currentRunWidth; } if (currentRun == maxRuns) { parentData._isVisible = false; if (indicator != null) { // this is the last visible run, add indicator: final indicatorParentData = indicator.parentData.toWrapParentData().._isVisible = true; final dx = _indicatorPosition == ExpansionWrapIndicatorPosition.border ? availableWidth - indicatorWith : currentRunWidth + spacing; indicatorParentData.offset = Offset( dx, currentRunY + (currentRunHeight - indicatorSize.height) / 2, ); } crossAxisMaxInCompressedState = currentRunY + currentRunHeight + runSpacing; } currentRunY += currentRunHeight + runSpacing; currentRunWidth = 0.0; currentRunHeight = 0.0; currentRunNumberOfChildren = 0; currentRun++; } parentData.offset = Offset(currentRunWidth + spacing, currentRunY); if (childSize.height > currentRunHeight) { currentRunHeight = childSize.height; } currentRunNumberOfChildren++; currentRunWidth += childSize.width + spacing; } } if (_indicatorPosition == ExpansionWrapIndicatorPosition.border) { maxRunWidth = availableWidth; } if (expanded && currentRun >= originalMaxRuns && indicator != null) { // add compress indicator at the end: final indicatorParentData = indicator.parentData.toWrapParentData() .._isVisible = true; final dx = _indicatorPosition == ExpansionWrapIndicatorPosition.border ? availableWidth - indicatorWith : currentRunWidth + spacing; indicatorParentData.offset = Offset( dx, currentRunY + (currentRunHeight - indicatorSize.height) / 2, ); } if (!expanded && currentRun <= originalMaxRuns && indicator != null) { indicator.parentData.isVisible = false; } size = crossAxisMaxInCompressedState != null ? constraints .constrain(Size(maxRunWidth, crossAxisMaxInCompressedState)) : constraints .constrain(Size(maxRunWidth, currentRunY + currentRunHeight)); } @override void paint(PaintingContext context, Offset offset) { void doPaint(RenderBox? child) { if (child != null) { final parentData = child.parentData; if (parentData is _WrapParentData && parentData._isVisible) { context.paintChild(child, parentData.offset + offset); } } } final children = _wrapChildren; if (children != null) { children.forEach(doPaint); } doPaint(_expandIndicator); doPaint(_compressIndicator); } @override bool hitTestSelf(Offset position) => true; @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { for (final RenderBox child in _allChildren) { final parentData = child.parentData; final bool isHit = parentData is _WrapParentData && parentData._isVisible && result.addWithPaintOffset( offset: parentData.offset, position: position, hitTest: (BoxHitTestResult result, Offset transformed) { assert(transformed == position - parentData.offset); return child.hitTest(result, position: transformed); }, ); if (isHit) return true; } return false; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/lock/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$appLockHash() => r'f41ef0732f43fae14f10611015d2415d32463a70'; /// Checks the app life cycle and displays the lock screen if needed /// /// Copied from [AppLock]. @ProviderFor(AppLock) final appLockProvider = NotifierProvider<AppLock, void>.internal( AppLock.new, name: r'appLockProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$appLockHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$AppLock = Notifier<void>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/lock/view.dart
import 'package:enough_platform_widgets/platform.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/app_localizations.g.dart'; import '../localization/extension.dart'; import '../screens/base.dart'; import 'service.dart'; /// Displays a lock screen class LockScreen extends StatefulHookConsumerWidget { /// Creates a new [LockScreen] const LockScreen({super.key}); static var _isShown = false; /// Is the lock screen currently shown? static bool get isShown => _isShown; @override ConsumerState<LockScreen> createState() => _LockScreenState(); } class _LockScreenState extends ConsumerState<LockScreen> { @override void initState() { super.initState(); LockScreen._isShown = true; } @override void dispose() { LockScreen._isShown = false; super.dispose(); } @override Widget build(BuildContext context) { final localizations = ref.text; return BasePage( includeDrawer: false, title: localizations.lockScreenTitle, content: _buildContent(context, localizations), ); } Widget _buildContent(BuildContext context, AppLocalizations localizations) => WillPopScope( onWillPop: () => Future.value(false), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(PlatformInfo.isCupertino ? CupertinoIcons.lock : Icons.lock), Padding( padding: const EdgeInsets.all(32), child: Text(localizations.lockScreenIntro), ), PlatformTextButton( child: Text(localizations.lockScreenUnlockAction), onPressed: () => _authenticate(context), ), ], ), ), ); Future<void> _authenticate(BuildContext context) async { final didAuthenticate = await BiometricsService.instance.authenticate(ref.text); if (didAuthenticate && context.mounted) { context.pop(); } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/lock/service.dart
import 'dart:async'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/foundation.dart'; import 'package:local_auth/local_auth.dart'; import '../localization/app_localizations.g.dart'; /// Handles biometrics class BiometricsService { /// Creates a new [BiometricsService] BiometricsService._(); static final _instance = BiometricsService._(); /// The instance of the [BiometricsService] static BiometricsService get instance => _instance; bool _isResolved = false; bool _isSupported = false; final _localAuth = LocalAuthentication(); /// Checks if the device supports biometrics Future<bool> isDeviceSupported() async { if (_isResolved) { return _isSupported; } try { final canCheck = await _localAuth.canCheckBiometrics; final isDeviceSupported = await _localAuth.isDeviceSupported(); _isSupported = canCheck && isDeviceSupported; } catch (e, s) { if (kDebugMode) { print('Unable to check local auth for biometrics support: $e $s'); _isSupported = false; } } _isResolved = true; return _isSupported; } /// Authenticates the user with biometrics Future<bool> authenticate( AppLocalizations localizations, { String? reason, }) async { if (!_isResolved) { await isDeviceSupported(); } if (!_isSupported) { return false; } // AppService.instance.ignoreBiometricsCheckAtNextResume = true; try { final result = await _localAuth.authenticate( localizedReason: reason ?? await _getLocalizedUnlockReason(localizations), options: const AuthenticationOptions( sensitiveTransaction: false, ), ); // unawaited(Future.delayed(const Duration(seconds: 2)).then( // (_) => AppService.instance.ignoreBiometricsCheckAtNextResume = false, // )); return result; } catch (e, s) { if (kDebugMode) { print('Authentication failed with $e $s'); } } return false; } Future<String> _getLocalizedUnlockReason( AppLocalizations localizations, ) async { if (PlatformInfo.isCupertino) { final availableBiometrics = await _localAuth.getAvailableBiometrics(); if (availableBiometrics.contains(BiometricType.face)) { return localizations.securityUnlockWithFaceId; } else if (availableBiometrics.contains(BiometricType.fingerprint)) { return localizations.securityUnlockWithTouchId; } } return localizations.securityUnlockReason; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/lock/provider.dart
import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../app_lifecycle/provider.dart'; import '../localization/extension.dart'; import '../logger.dart'; import '../routes/routes.dart'; import '../screens/screens.dart'; import '../settings/model.dart'; import '../settings/provider.dart'; import 'service.dart'; part 'provider.g.dart'; /// Checks the app life cycle and displays the lock screen if needed @Riverpod(keepAlive: true) class AppLock extends _$AppLock { var _lockTime = DateTime.now(); static var _ignoreNextSettingsChange = false; /// Allows to ignore the next settings change // ignore: avoid_setters_without_getters static set ignoreNextSettingsChange(bool value) => _ignoreNextSettingsChange = value; @override void build() { final enableBiometricLock = ref.watch( settingsProvider.select((value) => value.enableBiometricLock), ); final lockTimePreference = ref.watch( settingsProvider.select((value) => value.lockTimePreference), ); final isResumed = ref.watch(appIsResumedProvider); if (!enableBiometricLock) { return; } if (_ignoreNextSettingsChange) { _ignoreNextSettingsChange = false; logger.d('ignoring settings change'); return; } final context = Routes.navigatorKey.currentContext; if (context == null) { return; } if (!isResumed) { _lockTime = DateTime.now(); logger.d( 'setting lock time: $_lockTime', ); if (lockTimePreference == LockTimePreference.immediately && !LockScreen.isShown) { logger.d('pushing lock screen (immediately + !isResumed)'); unawaited(context.pushNamed(Routes.lockScreen)); } } else { final difference = DateTime.now().difference(_lockTime); switch (lockTimePreference) { case LockTimePreference.immediately: if (!LockScreen.isShown) { logger.d('pushing lock screen (immediately + isResumed)'); unawaited(context.pushNamed(Routes.lockScreen)); } _unlock(context, ref); break; case LockTimePreference.after5minutes: if (difference.inMinutes >= 5) { if (!LockScreen.isShown) { logger.d('pushing lock screen 5min'); unawaited(context.pushNamed(Routes.lockScreen)); } _unlock(context, ref); } break; case LockTimePreference.after30minutes: if (difference.inMinutes >= 30) { if (!LockScreen.isShown) { logger.d('pushing lock screen 30min'); unawaited(context.pushNamed(Routes.lockScreen)); } _unlock(context, ref); } break; } } } Future<void> _unlock(BuildContext context, Ref ref) async { final localizations = ref.text; var isUnlocked = false; while (!isUnlocked) { ref.read(appLifecycleProvider.notifier).ignoreNextInactivationCycle(); isUnlocked = await BiometricsService.instance.authenticate(localizations); } if (isUnlocked && LockScreen.isShown) { if (context.mounted) { context.pop(); } } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/routes/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$routerConfigHash() => r'6f77b87a4a23f8d8541820bbb5111c7189151c66'; /// Provides the [GoRouter] configuration /// /// Copied from [routerConfig]. @ProviderFor(routerConfig) final routerConfigProvider = Provider<GoRouter>.internal( routerConfig, name: r'routerConfigProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$routerConfigHash, dependencies: null, allTransitiveDependencies: null, ); typedef RouterConfigRef = ProviderRef<GoRouter>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/routes/routes.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_media/enough_media.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import '../account/model.dart'; import '../models/models.dart'; import '../notification/model.dart'; /// Should the app drawer be used as root? /// /// This is `true` on Cupertino platforms. final useAppDrawerAsRoot = PlatformInfo.isCupertino; /// Defines app navigation routes class Routes { Routes._(); /// The root route static const String root = '/'; /// Displays the welcome screen static const String welcome = '/welcome'; /// Creates a new account static const String accountAdd = 'accountAdd'; /// Allows to edit a single account /// /// pathParameters: [pathParameterEmail] static const String accountEdit = 'edit'; /// Allows to edit a the account server settings /// /// pathParameters: [pathParameterEmail] or /// /// extra: [RealAccount] /// static const String accountServerDetails = 'serverDetails'; /// Displays inbox messages of the default account /// static const String mail = 'mail'; /// Displays inbox messages of the given account /// /// pathParameters: [pathParameterEmail] /// static const String mailForAccount = 'account'; /// Displays messages of the given account and mailbox /// /// pathParameters: [pathParameterEmail] and [pathParameterEncodedMailboxPath] /// static const String mailForMailbox = 'box'; /// Displays the settings static const String settings = 'settings'; /// Displays security settings static const String settingsSecurity = 'security'; /// Displays the settings for all accounts static const String settingsAccounts = 'accounts'; /// Displays theme settings static const String settingsDesign = 'design'; /// Displays feedback options static const String settingsFeedback = 'feedback'; /// Displays language settings static const String settingsLanguage = 'language'; /// Displays folder naming settings static const String settingsFolders = 'folders'; /// Displays read receipts settings static const String settingsReadReceipts = 'readReceipts'; /// Displays developer settings static const String settingsDevelopment = 'developerMode'; /// Displays swipe settings static const String settingsSwipe = 'swipe'; /// Displays signature settings static const String settingsSignature = 'signature'; /// Displays default sender settings static const String settingsDefaultSender = 'defaultSender'; /// Displays reply settings static const String settingsReplyFormat = 'replyFormat'; /// Displays a message source directly /// /// extra: [MessageSource] /// static const String messageSource = 'messageSource'; /// Displays a mail search /// /// extra: [MailSearch] /// static const String mailSearch = 'mailSearch'; /// Shows message details /// /// extra: [Message] /// /// queryParameters: [queryParameterBlockExternalContent] /// static const String mailDetails = 'mailDetails'; /// Loads message details from notification data /// /// extra: [MailNotificationPayload] /// /// queryParameters: [queryParameterBlockExternalContent] /// static const String mailDetailsForNotification = 'mailNotification'; /// Shows all message contents /// /// extra: [Message] /// static const String mailContents = 'mailContents'; /// Composes a new message /// /// extra: [ComposeData] /// static const String mailCompose = 'mailCompose'; /// Allows to pick a location /// /// Pops the [Uint8List] after selecting a location /// static const String locationPicker = 'locationPicker'; /// Displays interactive media /// /// extra: [InteractiveMediaWidget] /// static const String interactiveMedia = 'interactiveMedia'; /// Displays the source code of a message /// /// extra: [MimeMessage] /// static const String sourceCode = 'sourceCode'; /// Displays the web view based on the given configuration /// /// extra: [WebViewConfiguration] /// static const String webview = 'webview'; /// Displays the account and mailbox switcher on a separate screen. /// /// This is only applicable on iOS. static const String appDrawer = '/appDrawer'; /// Displays the lock screen static const String lockScreen = '/lock'; /// Path parameter name for an email address static const String pathParameterEmail = 'email'; /// Query parameter name for an encoded mailbox path static const String pathParameterEncodedMailboxPath = 'mailbox'; /// Query parameter to signal external images should be blocked static const String queryParameterBlockExternalContent = 'blockExternal'; /// The navigator key to use for routing when a widget's context is not /// mounted anymore static final navigatorKey = GlobalKey<NavigatorState>(); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/routes/provider.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_media/enough_media.dart'; import 'package:flutter/widgets.dart'; import 'package:go_router/go_router.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../account/model.dart'; import '../app.dart'; import '../models/compose_data.dart'; import '../models/message.dart'; import '../models/message_source.dart'; import '../models/web_view_configuration.dart'; import '../notification/model.dart'; import '../screens/screens.dart'; import '../settings/view/view.dart'; import '../widgets/app_drawer.dart'; import 'routes.dart'; part 'provider.g.dart'; /// Provides the [GoRouter] configuration @Riverpod(keepAlive: true) GoRouter routerConfig(RouterConfigRef ref) => standardRouterConfig; /// The standard [GoRouter] configuration GoRouter get standardRouterConfig => GoRouter( navigatorKey: Routes.navigatorKey, // redirect: (context, state) { // logger.d('redirect for ${state.uri}'); // return null; // }, routes: [ if (useAppDrawerAsRoot) ...[ _rootRoute, _appDrawerRoute, _lockRoute, _welcomeRoute, ] else ...[ _rootRoute, _accountAddRoute, _welcomeRoute, _mailRoute, _mailDetailsRoute, _mailDetailsForNotificationRoute, _mailContentsRoute, _sourceCodeRoute, _mailComposeRoute, _interactiveMediaRoute, _settingsRoute, _webviewRoute, _lockRoute, ], ], ); String _path(String routeName) => useAppDrawerAsRoot ? routeName : '/$routeName'; GoRoute get _rootRoute => GoRoute( path: Routes.root, builder: (context, state) => const InitializationScreen(), ); GoRoute get _appDrawerRoute => GoRoute( name: Routes.appDrawer, path: Routes.appDrawer, builder: (context, state) => const AppDrawer(), routes: [ _accountAddRoute, _mailRoute, _mailForAccountRoute, _mailDetailsRoute, _mailDetailsForNotificationRoute, _mailContentsRoute, _sourceCodeRoute, _mailComposeRoute, _interactiveMediaRoute, _settingsRoute, _webviewRoute, ], ); GoRoute get _accountAddRoute => GoRoute( name: Routes.accountAdd, path: _path(Routes.accountAdd), builder: (context, state) => const AccountAddScreen(), ); GoRoute get _welcomeRoute => GoRoute( name: Routes.welcome, path: Routes.welcome, builder: (context, state) => const WelcomeScreen(), ); GoRoute get _mailRoute => GoRoute( name: Routes.mail, path: _path(Routes.mail), builder: (context, state) => const MailScreenForDefaultAccount(), routes: [ if (!useAppDrawerAsRoot) _mailForAccountRoute, ], ); GoRoute get _mailForAccountRoute => GoRoute( name: Routes.mailForAccount, path: '${Routes.mailForAccount}/:${Routes.pathParameterEmail}', builder: (context, state) { final email = state.pathParameters[Routes.pathParameterEmail] ?? ''; return EMailScreen(key: ValueKey(email), email: email); }, routes: [ GoRoute( name: Routes.mailForMailbox, path: '${Routes.mailForMailbox}/' ':${Routes.pathParameterEncodedMailboxPath}', builder: (context, state) { final email = state.pathParameters[Routes.pathParameterEmail] ?? ''; final encodedMailboxPath = state.pathParameters[Routes.pathParameterEncodedMailboxPath] ?? ''; return EMailScreen( key: ValueKey('$email/$encodedMailboxPath'), email: email, encodedMailboxPath: encodedMailboxPath, ); }, ), GoRoute( name: Routes.messageSource, path: Routes.messageSource, builder: (context, state) { final extra = state.extra; return extra is MessageSource ? MessageSourceScreen(messageSource: extra) : const MailScreenForDefaultAccount(); }, ), GoRoute( name: Routes.mailSearch, path: Routes.mailSearch, builder: (context, state) { final extra = state.extra; return extra is MailSearch ? MailSearchScreen(search: extra) : const MailScreenForDefaultAccount(); }, ), GoRoute( name: Routes.accountEdit, path: Routes.accountEdit, builder: (context, state) => AccountEditScreen( accountEmail: state.pathParameters[Routes.pathParameterEmail] ?? '', ), ), GoRoute( name: Routes.accountServerDetails, path: Routes.accountServerDetails, builder: (context, state) { final email = state.pathParameters[Routes.pathParameterEmail]; if (email != null) { return AccountServerDetailsScreen( accountEmail: email, ); } final account = state.extra; if (account is RealAccount) { return AccountServerDetailsScreen( account: account, ); } return const MailScreenForDefaultAccount(); }, ), ], ); GoRoute get _mailComposeRoute => GoRoute( name: Routes.mailCompose, path: _path(Routes.mailCompose), builder: (context, state) { final data = state.extra; return data is ComposeData ? ComposeScreen(data: data) : const MailScreenForDefaultAccount(); }, routes: [ GoRoute( name: Routes.locationPicker, path: Routes.locationPicker, builder: (context, state) => const LocationScreen(), ), ], ); GoRoute get _mailDetailsRoute => GoRoute( name: Routes.mailDetails, path: _path(Routes.mailDetails), builder: (context, state) { final extra = state.extra; final blockExternalContent = state.uri .queryParameters[Routes.queryParameterBlockExternalContent] == 'true'; return extra is Message ? MessageDetailsScreen( message: extra, blockExternalContent: blockExternalContent, ) : const MailScreenForDefaultAccount(); }, ); GoRoute get _mailDetailsForNotificationRoute => GoRoute( name: Routes.mailDetailsForNotification, path: _path(Routes.mailDetailsForNotification), builder: (context, state) { final extra = state.extra; final blockExternalContent = state.uri .queryParameters[Routes.queryParameterBlockExternalContent] == 'true'; return extra is MailNotificationPayload ? MessageDetailsForNotificationScreen( payload: extra, blockExternalContent: blockExternalContent, ) : const MailScreenForDefaultAccount(); }, ); GoRoute get _mailContentsRoute => GoRoute( name: Routes.mailContents, path: _path(Routes.mailContents), builder: (context, state) { final extra = state.extra; return extra is Message ? MessageContentsScreen( message: extra, ) : const MailScreenForDefaultAccount(); }, ); GoRoute get _sourceCodeRoute => GoRoute( name: Routes.sourceCode, path: _path(Routes.sourceCode), builder: (context, state) { final mimeMessage = state.extra; return mimeMessage is MimeMessage ? SourceCodeScreen(mimeMessage: mimeMessage) : const MailScreenForDefaultAccount(); }, ); GoRoute get _interactiveMediaRoute => GoRoute( name: Routes.interactiveMedia, path: _path(Routes.interactiveMedia), builder: (context, state) { final widget = state.extra; return widget is InteractiveMediaWidget ? InteractiveMediaScreen(mediaWidget: widget) : const MailScreenForDefaultAccount(); }, ); GoRoute get _settingsRoute => GoRoute( name: Routes.settings, path: _path(Routes.settings), builder: (context, state) => const SettingsScreen(), routes: [ GoRoute( name: Routes.settingsAccounts, path: Routes.settingsAccounts, builder: (context, state) => const SettingsAccountsScreen(), ), GoRoute( name: Routes.settingsDefaultSender, path: Routes.settingsDefaultSender, builder: (context, state) => const SettingsDefaultSenderScreen(), ), GoRoute( name: Routes.settingsDesign, path: Routes.settingsDesign, builder: (context, state) => const SettingsDesignScreen(), ), GoRoute( name: Routes.settingsDevelopment, path: Routes.settingsDevelopment, builder: (context, state) => const SettingsDeveloperModeScreen(), ), GoRoute( name: Routes.settingsFeedback, path: Routes.settingsFeedback, builder: (context, state) => const SettingsFeedbackScreen(), ), GoRoute( name: Routes.settingsFolders, path: Routes.settingsFolders, builder: (context, state) => const SettingsFoldersScreen(), ), GoRoute( name: Routes.settingsLanguage, path: Routes.settingsLanguage, builder: (context, state) => const SettingsLanguageScreen(), ), GoRoute( name: Routes.settingsReadReceipts, path: Routes.settingsReadReceipts, builder: (context, state) => const SettingsReadReceiptsScreen(), ), GoRoute( name: Routes.settingsReplyFormat, path: Routes.settingsReplyFormat, builder: (context, state) => const SettingsReplyScreen(), ), GoRoute( name: Routes.settingsSecurity, path: Routes.settingsSecurity, builder: (context, state) => const SettingsSecurityScreen(), ), GoRoute( name: Routes.settingsSignature, path: Routes.settingsSignature, builder: (context, state) => const SettingsSignatureScreen(), ), GoRoute( name: Routes.settingsSwipe, path: Routes.settingsSwipe, builder: (context, state) => const SettingsSwipeScreen(), ), ], ); GoRoute get _lockRoute => GoRoute( name: Routes.lockScreen, path: Routes.lockScreen, builder: (context, state) => const LockScreen(), ); GoRoute _webviewRoute = GoRoute( name: Routes.webview, path: _path(Routes.webview), builder: (context, state) { final configuration = state.extra; return configuration is WebViewConfiguration ? WebViewScreen(configuration: configuration) : const MailScreenForDefaultAccount(); }, );
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/oauth/oauth.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter_web_auth/flutter_web_auth.dart'; import 'package:http/http.dart' as http; import '../keys/service.dart'; import '../logger.dart'; import '../util/http_helper.dart'; /// Defines the ID and secret of an OAuth client class OauthClientId { /// Creates a new [OauthClientId] const OauthClientId(this.id, this.secret); /// The ID of the OAuth client final String id; /// The secret of the OAuth client final String? secret; } /// Provides means to authenticate with an OAuth provider /// and to refresh the access token abstract class OauthClient { /// Creates a new [OauthClient] OauthClient(this.incomingHostName); /// The hostname of the incoming mail server final String incomingHostName; /// Whether this client is enabled bool get isEnabled => oauthClientId != null; /// The [OauthClientId] for this client OauthClientId? get oauthClientId => KeyService.instance.oauth[incomingHostName]; /// Authenticates with the given [email] address Future<OauthToken?> authenticate(String email) async { try { final oauthClientId = this.oauthClientId; if (oauthClientId == null) { logger.d('no oauth client id for $incomingHostName'); return Future.value(); } final token = await _authenticate(oauthClientId, email, incomingHostName); logger.d( 'authenticated $email and received refresh ' 'token ${token.refreshToken}', ); return token; } catch (e, s) { logger.e('Unable to authenticate: $e', error: e, stackTrace: s); return Future.value(); } } /// Refreshes the given [token] Future<OauthToken?> refresh(OauthToken token) async { final oauthClientId = this.oauthClientId; if (oauthClientId == null) { logger.d('no oauth client id for $incomingHostName'); return Future.value(); } try { final refreshedToken = await _refresh( oauthClientId, token, incomingHostName, ); logger.d( 'refreshed token and received refresh token ' '${refreshedToken.refreshToken}', ); return refreshedToken; } catch (e, s) { logger.e('Unable to refresh tokens: $e', error: e, stackTrace: s); return Future.value(); } } /// Subclasses have to implement the actual authentication Future<OauthToken> _authenticate( OauthClientId oauthClientId, String email, String provider, ); /// Subclasses have to implement the actual token refresh Future<OauthToken> _refresh( OauthClientId oauthClientId, OauthToken token, String provider, ); } /// Provide Gmail OAuth authentication class GmailOAuthClient extends OauthClient { /// Creates a new [GmailOAuthClient] GmailOAuthClient() : super('imap.gmail.com'); @override Future<OauthToken> _authenticate( OauthClientId oauthClientId, String email, String provider, ) async { final clientId = oauthClientId.id; final callbackUrlScheme = clientId.split('.').reversed.join('.'); // Construct the url final uri = Uri.https('accounts.google.com', '/o/oauth2/v2/auth', { 'response_type': 'code', 'client_id': clientId, 'redirect_uri': '$callbackUrlScheme:/', 'scope': 'https://mail.google.com/', 'login_hint': email, }).toString(); // Present the dialog to the user final result = await FlutterWebAuth.authenticate( url: uri, callbackUrlScheme: callbackUrlScheme, ); // Extract code from resulting url final code = Uri.parse(result).queryParameters['code']; // Use this code to get an access token final response = await http.post( Uri.parse('https://oauth2.googleapis.com/token'), body: { 'client_id': clientId, 'redirect_uri': '$callbackUrlScheme:/', 'grant_type': 'authorization_code', 'code': code, }, ); // Get the access token from the response final text = response.text; if (response.statusCode != 200 || text == null) { logger.e('received status code ${response.statusCode} with $text'); throw StateError( 'Unable to get Google OAuth token with code $code, ' 'status code=${response.statusCode}, response=$text', ); } return OauthToken.fromText(text, provider: provider); } @override Future<OauthToken> _refresh( OauthClientId oauthClientId, OauthToken token, String provider, ) async { final clientId = oauthClientId.id; final callbackUrlScheme = clientId.split('.').reversed.join('.'); final response = await http.post( Uri.parse('https://oauth2.googleapis.com/token'), body: { 'client_id': clientId, 'redirect_uri': '$callbackUrlScheme:/', 'refresh_token': token.refreshToken, 'grant_type': 'refresh_token', }, ); final text = response.text; if (response.statusCode != 200 || text == null) { logger.e( 'refresh: received status code ${response.statusCode} with $text', ); throw StateError( 'Unable to refresh Google OAuth token $token, ' 'status code=${response.statusCode}, response=$text', ); } return OauthToken.fromText( text, provider: provider, refreshToken: token.refreshToken, ); } } /// Provide Outlook OAuth authentication class OutlookOAuthClient extends OauthClient { /// Creates a new [OutlookOAuthClient] OutlookOAuthClient() : super('outlook.office365.com'); // source: https://docs.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth static const String _scope = 'https://outlook.office.com/IMAP.AccessAsUser.All ' 'https://outlook.office.com/SMTP.Send offline_access'; @override Future<OauthToken> _authenticate( OauthClientId oauthClientId, String email, String provider, ) async { final clientId = oauthClientId.id; final clientSecret = oauthClientId.secret; const callbackUrlScheme = 'maily://oauth'; // Construct the url final uri = Uri.https( // cSpell: disable-next-line 'login.microsoftonline.com', '/common/oauth2/v2.0/authorize', { 'response_type': 'code', 'client_id': clientId, 'client_secret': clientSecret, 'redirect_uri': callbackUrlScheme, 'scope': _scope, 'login_hint': email, }, ).toString(); // print('authenticate URL: $uri'); // Present the dialog to the user final result = await FlutterWebAuth.authenticate( url: uri, callbackUrlScheme: 'maily', //callbackUrlScheme, ); // Extract code from resulting url final code = Uri.parse(result).queryParameters['code']; // Use this code to get an access token final response = await http.post( Uri.parse('https://login.microsoftonline.com/common/oauth2/v2.0/token'), body: { 'client_id': clientId, 'redirect_uri': callbackUrlScheme, 'grant_type': 'authorization_code', 'code': code, }, ); // Get the access token from the response final responseText = response.text; if (responseText == null) { throw StateError( 'no response from ' 'https://login.microsoftonline.com/common/oauth2/v2.0/token', ); } return OauthToken.fromText(responseText, provider: provider); } @override Future<OauthToken> _refresh( OauthClientId oauthClientId, OauthToken token, String provider, ) async { final clientId = oauthClientId.id; final response = await http.post( Uri.parse('https://login.microsoftonline.com/common/oauth2/v2.0/token'), body: { 'client_id': clientId, 'scope': _scope, 'refresh_token': token.refreshToken, 'grant_type': 'refresh_token', }, ); final text = response.text; if (response.statusCode != 200 || text == null) { throw StateError( 'Unable to refresh Outlook OAuth token $token, ' 'status code=${response.statusCode}, response=$text', ); } return OauthToken.fromText( text, provider: provider, refreshToken: token.refreshToken, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/share/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$incomingShareHash() => r'03f2400b8aceda31ac2003e168a460d08499c7be'; /// Handles incoming shares /// /// Copied from [IncomingShare]. @ProviderFor(IncomingShare) final incomingShareProvider = AsyncNotifierProvider<IncomingShare, void>.internal( IncomingShare.new, name: r'incomingShareProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$incomingShareHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$IncomingShare = AsyncNotifier<void>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/share/provider.dart
import 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:go_router/go_router.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../account/provider.dart'; import '../app_lifecycle/provider.dart'; import '../logger.dart'; import '../models/compose_data.dart'; import '../routes/routes.dart'; import 'model.dart'; part 'provider.g.dart'; /// Callback to register a share handler typedef SharedDataCallback = Future<void> Function(List<SharedData> sharedData); /// Allows to registered shared data callbacks SharedDataCallback? onSharedData; /// Handles incoming shares @Riverpod(keepAlive: true) class IncomingShare extends _$IncomingShare { static const _platform = MethodChannel('app.channel.shared.data'); var _isFirstBuild = true; @override Future<void> build() async { final isResumed = ref.watch(rawAppLifecycleStateProvider .select((value) => value == AppLifecycleState.resumed)); if (isResumed) { if (Platform.isAndroid) { final shared = await _platform.invokeMethod('getSharedData'); logger.d('checkForShare: received data: $shared'); if (shared != null) { if (_isFirstBuild) { _isFirstBuild = false; await Future.delayed(const Duration(seconds: 2)); } await _composeWithSharedData(shared); } } } } Future<void> _composeWithSharedData( Map<dynamic, dynamic> shared, ) async { final sharedData = await _collectSharedData(shared); if (sharedData.isEmpty) { return; } final callback = onSharedData; if (callback != null) { return callback(sharedData); } else { MessageBuilder builder; final firstData = sharedData.first; final account = ref.read(currentRealAccountProvider); if (firstData is SharedMailto && account != null) { builder = MessageBuilder.prepareMailtoBasedMessage( firstData.mailto, account.fromAddress, ); } else { builder = MessageBuilder(); for (final data in sharedData) { await data.addToMessageBuilder(builder); } } final composeData = ComposeData(null, builder, ComposeAction.newMessage); final context = Routes.navigatorKey.currentContext; if (context != null && context.mounted) { unawaited(context.pushNamed(Routes.mailCompose, extra: composeData)); } } } Future<List<SharedData>> _collectSharedData( Map<dynamic, dynamic> shared, ) async { final sharedData = <SharedData>[]; final String? mimeTypeText = shared['mimeType']; final mediaType = (mimeTypeText == null || mimeTypeText.contains('*')) ? null : MediaType.fromText(mimeTypeText); final int? length = shared['length']; final String? text = shared['text']; if (kDebugMode) { print('share text: "$text"'); } if (length != null && length > 0) { for (var i = 0; i < length; i++) { final String? filename = shared['name.$i']; final Uint8List? data = shared['data.$i']; final String? typeName = shared['type.$i']; final localMediaType = (typeName != null && typeName != 'null') ? MediaType.fromText(typeName) : mediaType ?? (filename != null ? MediaType.guessFromFileName(filename) : MediaType.textPlain); sharedData.add(SharedBinary(data, filename, localMediaType)); if (kDebugMode) { print( 'share: loaded ${localMediaType.text} "$filename" ' 'with ${data?.length} bytes', ); } } } else if (text != null) { if (text.startsWith('mailto:')) { final mailto = Uri.parse(text); sharedData.add(SharedMailto(mailto)); } else { sharedData.add(SharedText(text, mediaType, subject: shared['subject'])); } } return sharedData; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/share/model.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:enough_html_editor/enough_html_editor.dart'; import 'package:enough_mail/enough_mail.dart'; /// State of a shared data item enum SharedDataAddState { /// The item was added added, /// The item was not added notAdded, } /// Result of adding a shared data item class SharedDataAddResult { /// Creates a new [SharedDataAddResult] const SharedDataAddResult(this.state, [this.details]); /// The item was added static const added = SharedDataAddResult(SharedDataAddState.added); /// The item was not added static const notAdded = SharedDataAddResult(SharedDataAddState.notAdded); /// The state of the item final SharedDataAddState state; /// The details of the item final dynamic details; } /// Shared data item abstract class SharedData { /// Creates a new [SharedData] SharedData(this.mediaType); /// The media type of the item, e.g. `image/jpeg` final MediaType mediaType; /// Adds the item to the message builder Future<SharedDataAddResult> addToMessageBuilder(MessageBuilder builder); /// Adds the item to the editor Future<SharedDataAddResult> addToEditor(HtmlEditorApi editorApi); } /// Shared data item for a file class SharedFile extends SharedData { /// Creates a new [SharedFile] SharedFile(this.file, MediaType? mediaType) : super(mediaType ?? MediaType.guessFromFileName(file.path)); /// The file final File file; @override Future<SharedDataAddResult> addToMessageBuilder( MessageBuilder builder, ) async { await builder.addFile(file, mediaType); return SharedDataAddResult.added; } @override Future<SharedDataAddResult> addToEditor(HtmlEditorApi editorApi) async { if (mediaType.isImage) { await editorApi.insertImageFile( file, mediaType.sub.mediaType.toString(), ); return SharedDataAddResult.added; } return SharedDataAddResult.notAdded; } } /// Shared data item for a binary class SharedBinary extends SharedData { /// Creates a new [SharedBinary] SharedBinary(this.data, this.filename, MediaType mediaType) : super(mediaType); /// The binary data final Uint8List? data; /// The optional filename final String? filename; @override Future<SharedDataAddResult> addToMessageBuilder( MessageBuilder builder, ) async { final data = this.data; if (data == null) { return SharedDataAddResult.notAdded; } builder.addBinary(data, mediaType, filename: filename); return SharedDataAddResult.added; } @override Future<SharedDataAddResult> addToEditor(HtmlEditorApi editorApi) async { final data = this.data; if (data != null && mediaType.isImage) { await editorApi.insertImageData( data, mediaType.sub.mediaType.toString(), ); return SharedDataAddResult.added; } return SharedDataAddResult.notAdded; } } /// Shared data item for a text class SharedText extends SharedData { /// Creates a new [SharedText] SharedText( this.text, MediaType? mediaType, { this.subject, }) : super(mediaType ?? MediaType.textPlain); /// The text final String text; /// The optional subject final String? subject; @override Future<SharedDataAddResult> addToMessageBuilder(MessageBuilder builder) { builder.text = text; if (subject != null) { builder.subject = subject; } return Future.value(SharedDataAddResult.added); } @override Future<SharedDataAddResult> addToEditor(HtmlEditorApi editorApi) async { await editorApi.insertText(text); return Future.value(SharedDataAddResult.added); } } /// Shared data item for a mailto link class SharedMailto extends SharedData { /// Creates a new [SharedMailto] SharedMailto(this.mailto) : super(MediaType.fromSubtype(MediaSubtype.textHtml)); /// The mailto link final Uri mailto; @override Future<SharedDataAddResult> addToEditor(HtmlEditorApi editorApi) { // TODO(RV): implement addToEditor throw UnimplementedError(); } @override Future<SharedDataAddResult> addToMessageBuilder(MessageBuilder builder) { // TODO(RV): implement addToMessageBuilder throw UnimplementedError(); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/date_sectioned_message_source.dart
import 'dart:math'; import 'package:flutter/foundation.dart'; import '../localization/app_localizations.g.dart'; import '../util/date_helper.dart'; import 'message.dart'; import 'message_date_section.dart'; import 'message_source.dart'; class DateSectionedMessageSource extends ChangeNotifier { DateSectionedMessageSource( this.messageSource, { required this.firstDayOfWeek, }) { messageSource.addListener(_update); } final int firstDayOfWeek; final MessageSource messageSource; int _numberOfSections = 0; int get size { final sourceSize = messageSource.size; if (sourceSize == 0) { return 0; } return sourceSize + _numberOfSections; } late List<MessageDateSection> _sections; bool isInitialized = false; var _isDisposed = false; Future<void> init() async { try { await messageSource.init(); _sections = await downloadDateSections(); _numberOfSections = _sections.length; isInitialized = true; if (!_isDisposed) { notifyListeners(); } } catch (e, s) { if (kDebugMode) { print('unexpected error $e at $s'); } } } Future<void> refresh() async { try { _numberOfSections = 0; await messageSource.refresh(); _sections = await downloadDateSections(); _numberOfSections = _sections.length; isInitialized = true; if (!_isDisposed) { notifyListeners(); } } catch (e, s) { if (kDebugMode) { print('unexpected error $e at $s'); } } } @override void dispose() { messageSource.removeListener(_update); _isDisposed = true; super.dispose(); } Future<List<MessageDateSection>> downloadDateSections({ int numberOfMessagesToBeConsidered = 40, }) async { final max = messageSource.size; final usedNumberOfMessagesToBeConsidered = (numberOfMessagesToBeConsidered > max) ? max : numberOfMessagesToBeConsidered; final messages = <Message>[]; for (var i = 0; i < usedNumberOfMessagesToBeConsidered; i++) { final message = await messageSource.getMessageAt(i); messages.add(message); } return getDateSections(messages); } List<MessageDateSection> getDateSections( List<Message> messages, ) { final sections = <MessageDateSection>[]; DateSectionRange? lastRange; int foundSections = 0; for (var i = 0; i < messages.length; i++) { final message = messages[i]; final dateTime = message.mimeMessage.decodeDate(); if (dateTime != null) { final range = DateHelper(firstDayOfWeek).determineDateSection(dateTime); if (range != lastRange) { final index = (lastRange == null) ? 0 : i + foundSections; sections.add(MessageDateSection(range, dateTime, index)); foundSections++; } lastRange = range; } } return sections; } SectionElement? getCachedElementAt(int index) { var messageIndex = index; if (_numberOfSections >= 0) { for (var i = 0; i < _numberOfSections; i++) { final section = _sections[i]; if (section.sourceStartIndex == index) { return SectionElement(section, null); } if (section.sourceStartIndex > index) { break; } messageIndex--; } } final message = messageSource.cache[messageIndex]; if (message != null) { return SectionElement(null, message); } return null; } Future<SectionElement> getElementAt(int index) async { var messageIndex = index; if (_numberOfSections >= 0) { for (var i = 0; i < _numberOfSections; i++) { final section = _sections[i]; if (section.sourceStartIndex == index) { return SectionElement(section, null); } if (section.sourceStartIndex > index) { break; } messageIndex--; } } final message = await messageSource.getMessageAt(messageIndex); return SectionElement(null, message); } Future<List<Message>> getMessagesForSection( MessageDateSection section, ) async { final index = _sections.indexOf(section); if (index == -1) { return []; } final startIndex = section.sourceStartIndex - index; final endIndex = (index < _sections.length - 1) ? _sections[index + 1].sourceStartIndex - index - 1 : min(startIndex + 5, messageSource.size); final futures = <Future<Message>>[]; for (var i = startIndex; i < endIndex; i++) { futures.add(messageSource.getMessageAt(i)); } final messages = await Future.wait(futures); return messages; } List<Message> _getTopMessages(int length) { final max = messageSource.size; final usedLength = (length > max) ? max : length; final messages = <Message>[]; for (int i = 0; i < usedLength; i++) { final message = messageSource.cache[i]; if (message != null) { messages.add(message); } } return messages; } void _update() { _sections = getDateSections(_getTopMessages(40)); _numberOfSections = _sections.length; notifyListeners(); } Future<void> deleteMessage(AppLocalizations localizations, Message message) => messageSource.deleteMessages( localizations, [message], localizations.resultDeleted, ); } class SectionElement { SectionElement(this.section, this.message); final MessageDateSection? section; final Message? message; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/sender.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import '../account/model.dart'; /// Contains information about a sender for composing new messages @immutable class Sender { /// Creates a new sender Sender( this.address, this.account, { this.isPlaceHolderForPlusAlias = false, }) : emailLowercase = address.email.toLowerCase(); /// The address final MailAddress address; /// The associated account final RealAccount account; /// Whether this sender is a placeholder for a plus alias final bool isPlaceHolderForPlusAlias; /// The lowercase email address for comparisons final String emailLowercase; @override String toString() => address.toString(); @override int get hashCode => emailLowercase.hashCode; @override bool operator ==(Object other) => other is Sender && other.emailLowercase == emailLowercase; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/compose_data.dart
import 'package:enough_mail/enough_mail.dart'; import 'message.dart'; enum ComposeAction { answer, forward, newMessage } enum ComposeMode { plainText, html } typedef MessageFinalizer = void Function(MessageBuilder messageBuilder); class ComposeData { ComposeData( this.originalMessages, this.messageBuilder, this.action, { this.resumeText, this.future, this.finalizers, this.composeMode = ComposeMode.html, }); Message? get originalMessage { final originalMessages = this.originalMessages; return (originalMessages != null && originalMessages.isNotEmpty) ? originalMessages.first : null; } final List<Message?>? originalMessages; final MessageBuilder messageBuilder; final ComposeAction action; final String? resumeText; final Future? future; final ComposeMode composeMode; List<MessageFinalizer>? finalizers; ComposeData resume(String text, {ComposeMode? composeMode}) => ComposeData( originalMessages, messageBuilder, action, resumeText: text, finalizers: finalizers, composeMode: composeMode ?? this.composeMode, ); /// Adds a finalizer /// /// A finalizer will be called before generating the final message. /// /// This can be used to update the message builder depending on the /// chosen sender or recipients, etc. void addFinalizer(MessageFinalizer finalizer) { final finalizers = (this.finalizers ?? <MessageFinalizer>[]) ..add(finalizer); this.finalizers = finalizers; } /// Finalizes the message builder. /// /// Compare [addFinalizer] void finalize() { final finalizers = this.finalizers; if (finalizers != null) { for (final finalizer in finalizers) { finalizer(messageBuilder); } } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/offline_mime_storage.dart
import 'dart:async'; import 'package:enough_mail/enough_mail.dart'; /// Provides persistence storage for mime messages abstract class OfflineMimeStorage { const OfflineMimeStorage(); /// Initializes this offline storage Future<void> init(); /// Cleans up the storage when the [account] has been removed Future<void> onAccountRemoved(); /// Saves the contents of the given [mimeMessage] Future<void> saveMessageContents(MimeMessage mimeMessage); /// Fetches the message contents for the partial [mimeMessage]. Future<MimeMessage?> fetchMessageContents( MimeMessage mimeMessage, { bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, }); /// Saves the given list of mime message envelope data Future<void> saveMessageEnvelopes( List<MimeMessage> messages, ); /// Load the mime message envelopes for the given [account] and [mailbox] Future<List<MimeMessage>?> loadMessageEnvelopes( MessageSequence sequence, ); /// Deletes the given [message]. Future<void> deleteMessage(MimeMessage message); /// Moves the [messages] into the [targetMailbox] Future<void> moveMessages(List<MimeMessage> messages, Mailbox targetMailbox); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/async_mime_source.dart
import 'dart:async'; import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import '../logger.dart'; import '../util/indexed_cache.dart'; /// Let other classes get notified about changes in a mime source abstract class MimeSourceSubscriber { /// Notifies about a single new message void onMailArrived(MimeMessage mime, AsyncMimeSource source, {int index = 0}); /// Notifies about a single removed message void onMailVanished(MimeMessage mime, AsyncMimeSource source); /// Notifies about a flags change for a single message void onMailFlagsUpdated(MimeMessage mime, AsyncMimeSource source); /// Notifies about the required to reload the cache void onMailCacheInvalidated(AsyncMimeSource source); } /// Defines a low level mime message source abstract class AsyncMimeSource { /// Creates a new mime source AsyncMimeSource() { logger.d('Creating $this / $runtimeType'); } /// The mail client associated with this source MailClient get mailClient; /// Retrieves the mailbox associated with this source Mailbox get mailbox; /// The name of this source String get name; /// Retrieves the size of this source int get size; /// Is this a source of presumably spam messages? bool get isJunk; /// Is this a source of already deleted messages? bool get isTrash; /// Is this a source of sent messages? bool get isSent; /// Is this a source of archived messages? bool get isArchive; /// Is this a source for inbox? bool get isInbox; /// Does this source support deleting all messages? bool get supportsDeleteAll; /// Does this source support message folders, e.g. for moving? bool get supportsMessageFolders; /// Does this source support [search]? bool get supportsSearching; /// Should external resources be blocked for this source? bool get shouldBlockImages => isJunk || isTrash; /// Searches this source, compare [supportsSearching] AsyncMimeSource search(MailSearch search); /// Initializes this mime source Future<void> init(); /// Retrieves the message at [index] Future<MimeMessage> getMessage(int index); /// Deletes the given [messages] /// /// Compare [deleteAllMessages] /// Compare [undoDeleteMessages] Future<DeleteResult> deleteMessages(List<MimeMessage> messages); /// Reverts the deletion as defined in the [deleteResult] Future<DeleteResult> undoDeleteMessages(DeleteResult deleteResult); /// Deletes all messages. /// /// Set [expunge] to `true` to wipe the folder. In that case /// the delete operation cannot be undone. /// /// Compare [deleteMessages] Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}); /// Moves [messages] to [targetMailbox] /// /// Compare [undoMoveMessages] /// Compare [moveMessagesToFlag] Future<MoveResult> moveMessages( List<MimeMessage> messages, Mailbox targetMailbox, ); /// Moves [messages] to the mailbox that is flagged with [targetMailboxFlag] /// /// Compare [undoMoveMessages] /// Compare [moveMessages] Future<MoveResult> moveMessagesToFlag( List<MimeMessage> messages, MailboxFlag targetMailboxFlag, ); /// Reverts the move as defined in the [moveResult] Future<MoveResult> undoMoveMessages(MoveResult moveResult); /// Adds or removes [flags] to/from the given [messages] Future<void> store( List<MimeMessage> messages, List<String> flags, { StoreAction action = StoreAction.add, }); /// Adds or removes [flags]to all messages Future<void> storeAll( List<String> flags, { StoreAction action = StoreAction.add, }); /// Fetches the message contents for the partial [message]. /// /// Compare [MailClient]'s `fetchMessageContents()` call. Future<MimeMessage> fetchMessageContents( MimeMessage message, { int? maxSize, bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, Duration? responseTimeout, }); /// Fetches a message part / attachment for the partial [mimeMessage]. /// /// Compare [MailClient]'s `fetchMessagePart()` call. Future<MimePart> fetchMessagePart( MimeMessage message, { required String fetchId, Duration? responseTimeout, }); /// Informs this source about a new incoming [message] /// at the optional [index]. /// /// Note this message does not necessarily match to this sources. Future<void> onMessageArrived(MimeMessage message, {int? index}); /// Informs this source about the [sequence] having been removed /// on the server. Future<void> onMessagesVanished(MessageSequence sequence); /// Is called when message flags have been updated on the server. Future<void> onMessageFlagsUpdated(MimeMessage message); /// Cleans up any resources void dispose(); /// Clears this source void clear(); /// Synchronizes messages manually after reconnecting to a mail service /// that does not support QRESYNC. /// /// This call will receive the latest 20 (or less) messages /// retrieved from the service. Future<void> resyncMessagesManually( List<MimeMessage> messages, ); final _subscribers = <MimeSourceSubscriber>[]; /// Adds a subscriber void addSubscriber(MimeSourceSubscriber subscriber) { _subscribers.add(subscriber); } /// Removes a subscriber void removeSubscriber(MimeSourceSubscriber subscriber) { _subscribers.remove(subscriber); } /// Notifies subscribers about a new mime message void notifySubscriberOnMessageArrived(MimeMessage mime) { for (final subscriber in _subscribers) { logger.d('$this: notify subscriber $subscriber'); subscriber.onMailArrived(mime, this); } } /// Notifies subscribers about a message that has been removed on the server void notifySubscribersOnMessageVanished(MimeMessage mime) { for (final subscriber in _subscribers) { subscriber.onMailVanished(mime, this); } } /// Notifies subscribers about a message for which the flags have changed /// on the server void notifySubscribersOnMessageFlagsUpdated(MimeMessage mime) { for (final subscriber in _subscribers) { subscriber.onMailFlagsUpdated(mime, this); } } /// Notifies subscribers about an invalidated cache for this source void notifySubscribersOnCacheInvalidated() { for (final subscriber in _subscribers) { subscriber.onMailCacheInvalidated(this); } } /// Sends the specified [message]. /// /// Use [MessageBuilder] to create new messages. /// /// Specify [from] as the originator in case it differs from the `From` /// header of the message. /// /// Optionally set [appendToSent] to `false` in case the message should NOT /// be appended to the SENT folder. /// By default the message is appended. Note that some mail providers /// automatically append sent messages to /// the SENT folder, this is not detected by this API. /// /// You can also specify if the message should be sent using 8 bit encoding /// with [use8BitEncoding], which default to `false`. /// /// Optionally specify the [recipients], in which case the recipients /// defined in the message are ignored. /// /// Optionally specify the [sentMailbox] when the mail system does not /// support mailbox flags. Future<void> sendMessage( MimeMessage message, { MailAddress? from, bool appendToSent = true, Mailbox? sentMailbox, bool use8BitEncoding = false, List<MailAddress>? recipients, }); } /// Keeps messages in a temporary cache abstract class CachedMimeSource extends AsyncMimeSource { /// Creates a new cached mime source CachedMimeSource({int maxCacheSize = IndexedCache.defaultMaxCacheSize}) : cache = IndexedCache<MimeMessage>(maxCacheSize: maxCacheSize); /// The cache for the received mime messages final IndexedCache<MimeMessage> cache; @override Future<MimeMessage> getMessage(int index) { final existingMessage = cache[index]; if (existingMessage != null) { return Future.value(existingMessage); } return loadMessage(index); } /// Loads the message at the given index Future<MimeMessage> loadMessage(int index); @override Future<void> onMessageArrived(MimeMessage message, {int? index}) async { final usedIndex = await addMessage(message, index: index); notifySubscriberOnMessageArrived(message); return handleOnMessageArrived(usedIndex, message); } /// Adds the [message] and retrieves the used cache index. Future<int> addMessage(MimeMessage message, {int? index}) { int findIndex(DateTime? messageDate) { if (messageDate == null) { return 0; } final now = DateTime.now(); var i = 0; while (cache[i] != null && (cache[i]?.decodeDate() ?? now).isAfter(messageDate)) { i++; } return i; } final usedIndex = index ?? findIndex(message.decodeDate()); cache.insert(usedIndex, message); return Future.value(usedIndex); } /// Handles a newly arrived message. /// /// Called from [onMessageArrived] Future<void> handleOnMessageArrived(int index, MimeMessage message); @override Future<void> onMessagesVanished(MessageSequence sequence) { bool uidMatcher(MimeMessage message, int uid) => message.uid == uid; bool sequenceIdMatcher(MimeMessage message, int sequenceId) => message.sequenceId == sequenceId; bool uidLargerMatcher(MimeMessage message, int uid) => (message.uid ?? 0) > uid; bool sequenceIdLargerMatcher(MimeMessage message, int sequenceId) => (message.sequenceId ?? 0) > sequenceId; final messages = <MimeMessage>[]; final equalsMatcher = sequence.isUidSequence ? uidMatcher : sequenceIdMatcher; final largerMatcher = sequence.isUidSequence ? uidLargerMatcher : sequenceIdLargerMatcher; final ids = sequence.toList()..sort((a, b) => b.compareTo(a)); for (final id in ids) { final mime = cache.removeFirstWhere((m) => equalsMatcher(m, id)); cache.forEachWhere( (m) => largerMatcher(m, id), (m) => m.sequenceId = (m.sequenceId ?? id) - 1, ); if (mime != null) { notifySubscribersOnMessageVanished(mime); messages.add(mime); } } return handleOnMessagesVanished(messages); } /// Handles messages being deleted from service. /// /// Is called from [onMessagesVanished] Future<void> handleOnMessagesVanished(List<MimeMessage> messages); /// Deletes the [messages] from the cache void removeFromCache(List<MimeMessage> messages) { for (final message in messages) { cache.removeFirstWhere((element) => element.guid == message.guid); } } @override void clear() { cache.clear(); } @override Future<void> onMessageFlagsUpdated(MimeMessage message) { final guid = message.guid; final sequenceId = message.sequenceId; final existing = guid != null ? cache.firstWhereOrNull( (element) => element.guid == guid, ) : cache.firstWhereOrNull( (element) => element.sequenceId == sequenceId, ); if (existing != null) { existing.flags = message.flags; } notifySubscribersOnMessageFlagsUpdated(existing ?? message); return Future.value(); } @override Future<void> resyncMessagesManually( List<MimeMessage> messages, ) async { // when mail server does not support QRESYNC, compare the latest messages // and check for changed flags (seen, flagged, ...) or vanished messages // fetch and compare the 20 latest messages: // For each message check for the following cases: // - message can be new (it will have a higher UID that the known // first message) // - message can have updated flags (GUID will still be the same) // - a previously cached message can now be deleted (sequence ID will match, // but not the UID/GUID) // // Additional complications occur when not the same number of first messages // are cached, // in that case the GUID/UID cannot be compared. // // Also, previously there might have been less messages in this // mime source than are now loaded. final firstCached = cache[0]; final firstCachedUid = firstCached?.uid; if (firstCachedUid == null) { // When the latest message is not known, better reload all. // TODO(RV): Should a reload also be triggered when other messages are // not cached? cache.clear(); notifySubscribersOnCacheInvalidated(); return init(); } // ensure not to change the underlying set of messages in case overrides // want to handle the messages as well: final messagesCopy = [...messages]; // detect new messages: final newMessages = messagesCopy .where((message) => (message.uid ?? 0) > firstCachedUid) .toList(); for (var i = newMessages.length; --i >= 0;) { final message = newMessages.elementAt(i); await onMessageArrived(message); messagesCopy.remove(message); } if (messagesCopy.isEmpty) { // only new messages have appeared... probably a sign to reload completely return; } final cachedMessages = List.generate( messagesCopy.length, (index) => cache[index + newMessages.length], ); // detect removed messages: final removedMessages = List<MimeMessage>.from( cachedMessages.where((cached) => cached != null && messagesCopy.firstWhereOrNull((m) => m.guid == cached.guid) == null), ); if (removedMessages.isNotEmpty) { final sequence = MessageSequence(isUidSequence: true); for (final removed in removedMessages) { final uid = removed.uid; if (uid != null) { sequence.add(uid); } cachedMessages.remove(removed); } if (sequence.isNotEmpty) { await onMessagesVanished(sequence); } } // detect messages with changed flags: final areListsEqual = const ListEquality().equals; for (final cached in cachedMessages) { if (cached != null) { final newMessage = messagesCopy.firstWhereOrNull((m) => m.guid == cached.guid); if (newMessage != null && !areListsEqual(newMessage.flags, cached.flags)) { await onMessageFlagsUpdated(newMessage); } } } } } /// Keeps messages in a temporary cache and accesses them page-wise abstract class PagedCachedMimeSource extends CachedMimeSource { /// Creates a new paged cached mime source PagedCachedMimeSource({ this.pageSize = 30, super.maxCacheSize, }); /// The size of a single page final int pageSize; final _pageLoadersByPageIndex = <int, Future<List<MimeMessage>>>{}; @override Future<MimeMessage> loadMessage(int index) async { Future<List<MimeMessage>> queue(int pageIndex) { final sequence = MessageSequence.fromPage(pageIndex + 1, pageSize, size); final future = loadMessages(sequence); _pageLoadersByPageIndex[pageIndex] = future; return future; } final pageIndex = index ~/ pageSize; final completer = _pageLoadersByPageIndex[pageIndex] ?? queue(pageIndex); try { final messages = await completer; final int pageEndIndex = pageIndex * pageSize + messages.length - 1; if (cache[pageEndIndex] == null) { // messages have not been added by another thread yet: final receivingDate = DateTime.now(); messages.sort((m1, m2) => (m1.decodeDate() ?? receivingDate) .compareTo(m2.decodeDate() ?? receivingDate)); await _pageLoadersByPageIndex.remove(pageIndex); for (int i = 0; i < messages.length; i++) { final cacheIndex = pageEndIndex - i; final message = messages[i]; cache[cacheIndex] = message; } } return messages[pageEndIndex - index]; } on MailException { await _pageLoadersByPageIndex.remove(pageIndex); rethrow; } } /// Loads the messages defined by the [sequence] Future<List<MimeMessage>> loadMessages(MessageSequence sequence); } /// Provides online access to a specific mailbox class AsyncMailboxMimeSource extends PagedCachedMimeSource { /// Creates a new mailbox source AsyncMailboxMimeSource(this.mailbox, this.mailClient); /// The mailbox @override final Mailbox mailbox; @override final MailClient mailClient; StreamSubscription<MailLoadEvent>? _mailLoadEventSubscription; StreamSubscription<MailVanishedEvent>? _mailVanishedEventSubscription; StreamSubscription<MailUpdateEvent>? _mailUpdatedEventSubscription; StreamSubscription<MailConnectionReEstablishedEvent>? _mailReconnectedEventSubscription; @override Future<void> init() { if (_mailLoadEventSubscription != null) { return Future.value(); } _registerEvents(); return mailClient.startPolling(); } @override void dispose() { _deregisterEvents(); } void _registerEvents() { _mailLoadEventSubscription = mailClient.eventBus.on<MailLoadEvent>().listen((event) { if (event.mailClient == mailClient) { onMessageArrived(event.message); } }); _mailVanishedEventSubscription = mailClient.eventBus.on<MailVanishedEvent>().listen((event) { final sequence = event.sequence; if (sequence != null && event.mailClient == mailClient) { onMessagesVanished(sequence); } }); _mailUpdatedEventSubscription = mailClient.eventBus.on<MailUpdateEvent>().listen((event) { if (event.mailClient == mailClient) { onMessageFlagsUpdated(event.message); } }); _mailReconnectedEventSubscription = mailClient.eventBus .on<MailConnectionReEstablishedEvent>() .listen(_onMailReconnected); } void _deregisterEvents() { _mailLoadEventSubscription?.cancel(); _mailVanishedEventSubscription?.cancel(); _mailUpdatedEventSubscription?.cancel(); _mailReconnectedEventSubscription?.cancel(); _mailLoadEventSubscription = null; _mailVanishedEventSubscription = null; _mailUpdatedEventSubscription = null; _mailReconnectedEventSubscription = null; } Future<void> _onMailReconnected( MailConnectionReEstablishedEvent event, ) async { if (event.mailClient == mailClient && event.isManualSynchronizationRequired) { final messages = await event.mailClient .fetchMessages(fetchPreference: FetchPreference.envelope); if (messages.isEmpty) { logger.w( 'MESSAGES ARE EMPTY FOR ' '${event.mailClient.lowLevelOutgoingMailClient.logName}', ); // since this is an unlikely outcome, the assumption is that this // an error and resync will be aborted, therefore. return; } await resyncMessagesManually(messages); } } @override Future<DeleteResult> deleteMessages(List<MimeMessage> messages) { removeFromCache(messages); final sequence = MessageSequence.fromMessages(messages); return mailClient.deleteMessages(sequence, messages: messages); } @override Future<DeleteResult> undoDeleteMessages(DeleteResult deleteResult) async { final result = await mailClient.undoDeleteMessages(deleteResult); await _reAddMessages(result); return result; } @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) async { clear(); mailbox.messagesExists = 0; final result = await mailClient.deleteAllMessages(mailbox, expunge: expunge); return [result]; } @override Future<MoveResult> moveMessages( List<MimeMessage> messages, Mailbox targetMailbox, ) { removeFromCache(messages); final sequence = MessageSequence.fromMessages(messages); return mailClient.moveMessages(sequence, targetMailbox, messages: messages); } @override Future<MoveResult> moveMessagesToFlag( List<MimeMessage> messages, MailboxFlag targetMailboxFlag, ) { removeFromCache(messages); final sequence = MessageSequence.fromMessages(messages); return mailClient.moveMessagesToFlag( sequence, targetMailboxFlag, messages: messages, ); } @override Future<MoveResult> undoMoveMessages(MoveResult moveResult) async { final result = await mailClient.undoMoveMessages(moveResult); await _reAddMessages(result); return result; } Future<void> _reAddMessages(MessagesOperationResult result) async { final messages = result.messages; if (messages != null) { for (final message in messages) { await addMessage(message); } } } @override Future<void> store( List<MimeMessage> messages, List<String> flags, { StoreAction action = StoreAction.add, }) { final sequence = MessageSequence.fromMessages(messages); return mailClient.store(sequence, flags, action: action); } @override Future<void> storeAll( List<String> flags, { StoreAction action = StoreAction.add, }) { final sequence = MessageSequence.fromAll(); return mailClient.store(sequence, flags, action: action); } @override bool get isArchive => mailbox.isArchive; @override bool get isJunk => mailbox.isJunk; @override bool get isSent => mailbox.isSent; @override bool get isTrash => mailbox.isTrash; @override bool get isInbox => mailbox.isInbox; @override String get name => mailbox.name; @override AsyncMimeSource search(MailSearch search) => AsyncSearchMimeSource(search, mailbox, mailClient, this); @override int get size => mailbox.messagesExists; @override bool get supportsDeleteAll => isTrash || isJunk; @override bool get supportsMessageFolders => (mailClient.mailboxes?.length ?? 0) > 0; @override bool get supportsSearching => true; @override Future<List<MimeMessage>> loadMessages(MessageSequence sequence) => mailClient.fetchMessageSequence( sequence, fetchPreference: FetchPreference.envelope, ); @override Future<void> handleOnMessageArrived(int index, MimeMessage message) => Future.value(); @override Future<void> handleOnMessagesVanished(List<MimeMessage> messages) => Future.value(); @override Future<MimeMessage> fetchMessageContents( MimeMessage message, { int? maxSize, bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, Duration? responseTimeout, }) => mailClient.fetchMessageContents( message, maxSize: maxSize, markAsSeen: markAsSeen, includedInlineTypes: includedInlineTypes, responseTimeout: responseTimeout, ); @override Future<MimePart> fetchMessagePart( MimeMessage message, { required String fetchId, Duration? responseTimeout, }) => mailClient.fetchMessagePart( message, fetchId, responseTimeout: responseTimeout, ); @override Future<void> sendMessage( MimeMessage message, { MailAddress? from, bool appendToSent = true, Mailbox? sentMailbox, bool use8BitEncoding = false, List<MailAddress>? recipients, }) => mailClient.sendMessage( message, from: from, appendToSent: appendToSent, sentMailbox: sentMailbox, use8BitEncoding: use8BitEncoding, recipients: recipients, ); @override String toString() => 'AsyncMailboxMimeSource(${mailClient.account.email}: ' '${mailbox.name})'; } /// Accesses search results class AsyncSearchMimeSource extends AsyncMimeSource { /// Creates a new search mime source AsyncSearchMimeSource( this.mailSearch, this.mailbox, this.mailClient, this.parent, ); /// The search terms final MailSearch mailSearch; /// The mailbox on which the search is done @override final Mailbox mailbox; /// The parent mime source final AsyncMimeSource parent; /// The search result late MailSearchResult searchResult; @override int get size => searchResult.length; @override final MailClient mailClient; @override Future<void> init() async { try { searchResult = await mailClient.searchMessages(mailSearch); } catch (e, s) { searchResult = MailSearchResult.empty(mailSearch); if (kDebugMode) { print('Unable to search: $e $s'); } } } @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) async { if (size == 0) { return []; } final sequence = searchResult.pagedSequence.sequence; clear(); final deleteResult = await mailClient.deleteMessages(sequence); return [deleteResult]; } @override bool get isArchive => mailbox.isArchive; @override bool get isJunk => mailbox.isJunk; @override bool get isTrash => mailbox.isTrash; @override bool get isSent => mailbox.isSent; @override bool get isInbox => mailbox.isInbox; @override String get name => mailSearch.query; @override bool get shouldBlockImages => isTrash || isJunk; @override bool get supportsSearching => false; @override bool get supportsDeleteAll => searchResult.isNotEmpty; @override void clear() { searchResult = MailSearchResult.empty(mailSearch); } @override Future<DeleteResult> deleteMessages(List<MimeMessage> messages) async { final sequence = MessageSequence.fromMessages(messages); searchResult.removeMessageSequence(sequence); return parent.deleteMessages(messages); } @override Future<DeleteResult> undoDeleteMessages(DeleteResult deleteResult) { // TODO(RV): add sequence back to search result - or rather // the sequence after undoing it //searchResult.addMessageSequence(deleteResult.originalSequence); return parent.undoDeleteMessages(deleteResult); } @override void dispose() { // nothing to dispose } @override Future<MimeMessage> getMessage(int index) => searchResult.getMessage(index, mailClient, mailbox: mailbox); @override Future<void> onMessageArrived(MimeMessage message, {int? index}) { if (mailSearch.matches(message)) { searchResult.addMessage(message); notifySubscriberOnMessageArrived(message); } return Future.value(); } @override Future<void> onMessageFlagsUpdated(MimeMessage message) { final uid = message.uid; final existing = searchResult.messages.firstWhereOrNull((m) => m.uid == uid); if (existing != null) { existing.flags = message.flags; notifySubscribersOnMessageFlagsUpdated(existing); } return Future.value(); } @override Future<void> onMessagesVanished(MessageSequence sequence) { if (sequence.isUidSequence == searchResult.pagedSequence.isUidSequence) { searchResult .removeMessageSequence(sequence) .forEach(notifySubscribersOnMessageVanished); } return Future.value(); } @override Future<void> store( List<MimeMessage> messages, List<String> flags, { StoreAction action = StoreAction.add, }) => parent.store(messages, flags, action: action); @override Future<void> storeAll( List<String> flags, { StoreAction action = StoreAction.add, }) async { final sequence = searchResult.pagedSequence.sequence; if (sequence.isEmpty) { return Future.value(); } await mailClient.store(sequence, flags, action: action); } @override bool get supportsMessageFolders => parent.supportsMessageFolders; @override Future<void> resyncMessagesManually(List<MimeMessage> messages) { // just redo the full search for now. notifySubscribersOnCacheInvalidated(); return init(); } @override AsyncMimeSource search(MailSearch search) { throw UnimplementedError(); } @override Future<MoveResult> moveMessages( List<MimeMessage> messages, Mailbox targetMailbox, ) { // TODO(RV): implement moveMessages throw UnimplementedError(); } @override Future<MoveResult> moveMessagesToFlag( List<MimeMessage> messages, MailboxFlag targetMailboxFlag, ) { // TODO(RV): implement moveMessagesToFlag throw UnimplementedError(); } @override Future<MoveResult> undoMoveMessages(MoveResult moveResult) { // TODO(RV): implement undoMoveMessages throw UnimplementedError(); } @override Future<MimeMessage> fetchMessageContents( MimeMessage message, { int? maxSize, bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, Duration? responseTimeout, }) => mailClient.fetchMessageContents( message, maxSize: maxSize, markAsSeen: markAsSeen, includedInlineTypes: includedInlineTypes, responseTimeout: responseTimeout, ); @override Future<MimePart> fetchMessagePart( MimeMessage message, { required String fetchId, Duration? responseTimeout, }) => mailClient.fetchMessagePart( message, fetchId, responseTimeout: responseTimeout, ); @override Future<void> sendMessage( MimeMessage message, { MailAddress? from, bool appendToSent = true, Mailbox? sentMailbox, bool use8BitEncoding = false, List<MailAddress>? recipients, }) => mailClient.sendMessage( message, from: from, appendToSent: appendToSent, sentMailbox: sentMailbox, use8BitEncoding: use8BitEncoding, recipients: recipients, ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/message_source.dart
import 'package:collection/collection.dart' show IterableExtension; import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import '../account/model.dart'; import '../localization/app_localizations.g.dart'; import '../logger.dart'; import '../notification/model.dart'; import '../notification/service.dart'; import '../scaffold_messenger/service.dart'; import '../util/indexed_cache.dart'; import 'async_mime_source.dart'; import 'message.dart'; /// Manages messages abstract class MessageSource extends ChangeNotifier implements MimeSourceSubscriber { /// Creates a new message source with the optional [parent]. /// /// Set [isSearch] to `true` in case this message source is deemed /// to be a search. MessageSource({MessageSource? parent, this.isSearch = false}) : _parentMessageSource = parent; /// Retrieves the parent source's name String? get parentName => _parentMessageSource?.name; /// The number of messages in this source int get size; /// Is the source empty? /// /// Compare [size] bool get isEmpty => size == 0; /// The cache for messages final cache = IndexedCache<Message>(); String? _description; /// the description of this source String? get description => _description; set description(String? value) { _description = value; notifyListeners(); } String? _name; /// The name of this source String? get name => _name; set name(String? value) { _name = value; notifyListeners(); } /// The account associated with this source Account get account; bool _supportsDeleteAll = false; /// Does this source support to delete all messages? /// /// Compare [deleteAllMessages] and [markAllMessagesSeen] bool get supportsDeleteAll => _supportsDeleteAll; set supportsDeleteAll(bool value) { _supportsDeleteAll = value; notifyListeners(); } final MessageSource? _parentMessageSource; /// Is this message source a search? final bool isSearch; bool get shouldBlockImages; bool get isJunk; bool get isArchive; bool get isTrash; bool get isSent; bool get supportsMessageFolders; bool get supportsSearching; /// Initializes this source Future<void> init(); /// Deletes all messages /// /// Only available when [supportsDeleteAll] is `true` Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}); /// Marks all messages as seen (read) `true` or unseen (unread) /// when `false` is given /// /// Only available when [supportsDeleteAll] is `true` Future<void> markAllMessagesSeen(bool seen); /// Retrieves the message for the given [index] Future<Message> getMessageAt(int index) async { var message = cache[index]; if (message == null) { message = await loadMessage(index); cache[index] = message; } return message; } /// Loads the message for the given [index] Future<Message> loadMessage(int index); /// Retrieves the next message Future<Message?> next(Message current) { if (current.sourceIndex >= size - 1) { return Future.value(); } return getMessageAt(current.sourceIndex + 1); } /// Retrieves the previous message Future<Message?> previous(Message current) { if (current.sourceIndex == 0) { return Future.value(); } return getMessageAt(current.sourceIndex - 1); } /// Retrieves the mime source for the given [message] AsyncMimeSource? getMimeSource(Message message); /// Removes the given message from the internally used cache bool removeFromCache(Message message, {bool notify = true}) { final removed = cache.remove(message); if (removed) { final sourceIndex = message.sourceIndex; cache.forEachWhere( (msg) => msg.sourceIndex > sourceIndex, (msg) => msg.sourceIndex--, ); } final parent = _parentMessageSource; if (parent != null) { final mime = message.mimeMessage; parent.removeMime(mime, getMimeSource(message)); } if (removed && notify) { notifyListeners(); } return removed; } @override void onMailFlagsUpdated(MimeMessage mime, AsyncMimeSource source) { final message = cache.getWithMime(mime, source); if (message != null) { message.updateFlags(mime.flags); } } @override void onMailVanished(MimeMessage mime, AsyncMimeSource source) { final message = cache.getWithMime(mime, source); if (message != null) { removeFromCache(message); } } @override void onMailArrived( MimeMessage mime, AsyncMimeSource source, { int index = 0, }) { // the source index is 0 since this is the new first message: final message = createMessage(mime, source, index); insertIntoCache(index, message); notifyListeners(); } /// Inserts the [message] at the given [index]. void insertIntoCache(int index, Message message) { cache.insert(index, message); } /// Deletes the given message /// /// Just forwards to [deleteMessages] @Deprecated('use deleteMessages instead') Future<void> deleteMessage(AppLocalizations localizations, Message message) => deleteMessages( localizations, [message], localizations.resultDeleted, ); /// Deletes the given messages Future<void> deleteMessages( AppLocalizations localizations, List<Message> messages, String notification, ) { final notificationService = NotificationService.instance; for (final message in messages) { _removeMessageFromCacheAndCancelNotification( message, notificationService, notify: false, ); } notifyListeners(); return _deleteMessages(localizations, messages, notification); } Future<void> _deleteMessages( AppLocalizations localizations, List<Message> messages, String notification, ) async { final messagesBySource = orderByMimeSource(messages); final resultsBySource = <AsyncMimeSource, DeleteResult>{}; for (final source in messagesBySource.keys) { final mimes = messagesBySource[source]!; final deleteResult = await source.deleteMessages(mimes); if (deleteResult.canUndo) { resultsBySource[source] = deleteResult; } } ScaffoldMessengerService.instance.showTextSnackBar( localizations, notification, undo: resultsBySource.isEmpty ? null : () async { for (final source in resultsBySource.keys) { await source.undoDeleteMessages(resultsBySource[source]!); } _reAddMessages(messages); notifyListeners(); }, ); } Future<void> markAsJunk(AppLocalizations localizations, Message message) => moveMessageToFlag( localizations, message, MailboxFlag.junk, localizations.resultMovedToJunk, ); Future<void> markAsNotJunk(AppLocalizations localizations, Message message) => moveMessageToFlag( localizations, message, MailboxFlag.inbox, localizations.resultMovedToInbox, ); Future<void> moveMessageToFlag( AppLocalizations localizations, Message message, MailboxFlag targetMailboxFlag, String notification, ) => moveMessage( localizations, message, message.source .getMimeSource(message) ?.mailClient .getMailbox(targetMailboxFlag) ?? Mailbox( encodedName: 'inbox', encodedPath: 'inbox', flags: [], pathSeparator: '/', ), notification, ); Future<void> moveMessage( AppLocalizations localizations, Message message, Mailbox targetMailbox, String notification, ) async { _removeMessageFromCacheAndCancelNotification( message, NotificationService.instance, notify: false, ); final mailClient = message.source.getMimeSource(message)?.mailClient; if (mailClient == null) { throw Exception('Unable to retrieve mime source for $message'); } final moveResult = await mailClient.moveMessage(message.mimeMessage, targetMailbox); notifyListeners(); if (moveResult.canUndo) { ScaffoldMessengerService.instance.showTextSnackBar( localizations, notification, undo: () async { await mailClient.undoMoveMessages(moveResult); insertIntoCache(message.sourceIndex, message); notifyListeners(); }, ); } } void _removeMessageFromCacheAndCancelNotification( Message message, NotificationService notificationService, { bool notify = true, }) { notificationService.cancelNotificationForMessage(message); removeFromCache(message, notify: notify); } Future<void> moveMessagesToFlag( AppLocalizations localizations, List<Message> messages, MailboxFlag targetMailboxFlag, String notification, ) async { final notificationService = NotificationService.instance; for (final message in messages) { _removeMessageFromCacheAndCancelNotification( message, notificationService, notify: false, ); } final messagesBySource = orderByMimeSource(messages); final resultsBySource = <AsyncMimeSource, MoveResult>{}; for (final source in messagesBySource.keys) { final messages = messagesBySource[source]!; final moveResult = await source.moveMessagesToFlag(messages, targetMailboxFlag); if (moveResult.canUndo) { resultsBySource[source] = moveResult; } } notifyListeners(); if (resultsBySource.isNotEmpty) { ScaffoldMessengerService.instance.showTextSnackBar( localizations, notification, undo: () async { for (final source in resultsBySource.keys) { await source.undoMoveMessages(resultsBySource[source]!); } _reAddMessages(messages); notifyListeners(); }, ); } } Future<void> moveMessages( AppLocalizations localizations, List<Message> messages, Mailbox targetMailbox, String notification, ) async { final notificationService = NotificationService.instance; for (final message in messages) { _removeMessageFromCacheAndCancelNotification( message, notificationService, notify: false, ); } final source = getMimeSource(messages.first); final parent = _parentMessageSource; if (source != null) { final mimes = messages.map((m) => m.mimeMessage).toList(); final moveResult = await source.moveMessages(mimes, targetMailbox); notifyListeners(); ScaffoldMessengerService.instance.showTextSnackBar( localizations, notification, undo: moveResult.canUndo ? () async { await source.undoMoveMessages(moveResult); _reAddMessages(messages); notifyListeners(); } : null, ); } else if (parent != null) { return parent.moveMessages( localizations, messages, targetMailbox, notification, ); } } void _reAddMessages(List<Message> messages) { messages.sort((m1, m2) => m1.sourceIndex.compareTo(m2.sourceIndex)); for (final message in messages) { insertIntoCache(message.sourceIndex, message); } } Future<void> moveToInbox( AppLocalizations localizations, Message message, ) async => moveMessageToFlag( localizations, message, MailboxFlag.inbox, localizations.resultMovedToInbox, ); Future<void> archive(AppLocalizations localizations, Message message) => moveMessageToFlag( localizations, message, MailboxFlag.archive, localizations.resultArchived, ); Future<void> markAsSeen(Message msg, bool isSeen) { final source = getMimeSource(msg); if (source != null) { onMarkedAsSeen(msg, isSeen); if (isSeen) { NotificationService.instance.cancelNotificationForMessage(msg); } return source.store( [msg.mimeMessage], [MessageFlags.seen], action: isSeen ? StoreAction.add : StoreAction.remove, ); } msg.isSeen = isSeen; final parent = _parentMessageSource; final parentMsg = parent?.cache.getWithMime(msg.mimeMessage, source); if (parent != null && parentMsg != null) { return parent.markAsSeen(parentMsg, isSeen); } return msg.source.storeMessageFlags( [msg], [MessageFlags.seen], action: isSeen ? StoreAction.add : StoreAction.remove, ); } void onMarkedAsSeen(Message msg, bool isSeen) { msg.isSeen = isSeen; final parent = _parentMessageSource; if (parent != null) { final parentMsg = parent.cache.getWithMime(msg.mimeMessage, getMimeSource(msg)); if (parentMsg != null) { return parent.onMarkedAsSeen(parentMsg, isSeen); } } } Future<void> markAsFlagged(Message msg, bool isFlagged) { onMarkedAsFlagged(msg, isFlagged); return msg.source.storeMessageFlags( [msg], [MessageFlags.flagged], action: isFlagged ? StoreAction.add : StoreAction.remove, ); } void onMarkedAsFlagged(Message msg, bool isFlagged) { msg.isFlagged = isFlagged; final parent = _parentMessageSource; if (parent != null) { final parentMsg = parent.cache.getWithMime( msg.mimeMessage, getMimeSource(msg), ); if (parentMsg != null) { parent.onMarkedAsFlagged(parentMsg, isFlagged); } } } Future<void> markMessagesAsSeen(List<Message> messages, bool isSeen) { final notificationService = NotificationService.instance; for (final msg in messages) { onMarkedAsSeen(msg, isSeen); if (isSeen) { notificationService.cancelNotificationForMessage(msg); } } return storeMessageFlags( messages, [MessageFlags.seen], action: isSeen ? StoreAction.add : StoreAction.remove, ); } Future<void> markMessagesAsFlagged(List<Message> messages, bool flagged) { for (final msg in messages) { msg.isFlagged = flagged; } return storeMessageFlags( messages, [MessageFlags.flagged], action: flagged ? StoreAction.add : StoreAction.remove, ); } Map<AsyncMimeSource, List<MimeMessage>> orderByMimeSource( List<Message> messages, ) { final mimesBySource = <AsyncMimeSource, List<MimeMessage>>{}; for (final message in messages) { final source = getMimeSource(message); if (source == null) { logger.w( 'unable to locate mime-source for ' 'message ${message.mimeMessage}', ); continue; } final existingMessages = mimesBySource[source]; if (existingMessages != null) { existingMessages.add(message.mimeMessage); } else { mimesBySource[source] = [message.mimeMessage]; } } return mimesBySource; } Future<void> storeMessageFlags( List<Message> messages, List<String> flags, { StoreAction action = StoreAction.add, }) { final messagesBySource = orderByMimeSource(messages); final futures = <Future<void>>[]; for (final source in messagesBySource.keys) { final messages = messagesBySource[source]!; final future = source.store(messages, flags, action: action); futures.add(future); } return Future.wait(futures); } MessageSource search(AppLocalizations localizations, MailSearch search); void removeMime(MimeMessage mimeMessage, AsyncMimeSource? mimeSource) { final existingMessage = cache.getWithMime(mimeMessage, mimeSource); if (existingMessage != null) { removeFromCache(existingMessage); } } Future<void> refresh() async { clear(); cache.clear(); await init(); notifyListeners(); } void clear(); /// Fetches the message contents for the partial [message]. /// /// Compare [MailClient]'s `fetchMessageContents()` call. Future<MimeMessage> fetchMessageContents( Message message, { int? maxSize, bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, Duration? responseTimeout, }) async { final mimeSource = getMimeSource(message); if (mimeSource == null) { throw Exception('Unable to detect mime source from $message'); } final mimeMessage = await mimeSource.fetchMessageContents( message.mimeMessage, maxSize: maxSize, markAsSeen: markAsSeen, includedInlineTypes: includedInlineTypes, responseTimeout: responseTimeout, ); message.updateMime(mimeMessage); return mimeMessage; } /// Fetches the message contents for the partial [message]. /// /// Compare [MailClient]'s `fetchMessagePart()` call. Future<MimePart> fetchMessagePart( Message message, { required String fetchId, Duration? responseTimeout, }) { final mimeSource = getMimeSource(message); if (mimeSource == null) { throw Exception('Unable to detect mime source from $message'); } return mimeSource.fetchMessagePart( message.mimeMessage, fetchId: fetchId, responseTimeout: responseTimeout, ); } /// Creates a new message /// /// Can be overridden by subclasses to create a custom message type Message createMessage( MimeMessage mime, AsyncMimeSource mimeSource, int index, ) => Message(mime, this, index); /// Loads the message source for the given [payload] Future<Message> loadSingleMessage(MailNotificationPayload payload) { throw UnimplementedError(); } // void replaceMime(Message message, MimeMessage mime) { // final mimeSource = getMimeSource(message); // remove(message); // mimeSource.addMessage(mime); // onMailAdded(mime, mimeSource); // } } class MailboxMessageSource extends MessageSource { MailboxMessageSource.fromMimeSource( this.mimeSource, String description, this.mailbox, { required this.account, super.parent, super.isSearch, }) { _description = description; _name = mailbox.name; mimeSource.addSubscriber(this); logger.d('Creating MailboxMessageSource for mimeSource $mimeSource'); } /// The associated mailbox final Mailbox mailbox; @override final RealAccount account; @override int get size => mimeSource.size; /// The mime source for this message source final AsyncMimeSource mimeSource; @override void dispose() { mimeSource ..removeSubscriber(this) ..dispose(); super.dispose(); } @override Future<Message> loadMessage(int index) async { //print('get uncached $index'); final mime = await mimeSource.getMessage(index); return Message(mime, this, index); } @override Future<void> init() async { await mimeSource.init(); name ??= mimeSource.name; supportsDeleteAll = mimeSource.supportsDeleteAll; } @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) async { final removedMessages = cache.getAllCachedEntries(); cache.clear(); final futureResults = mimeSource.deleteAllMessages(expunge: expunge); clear(); logger ..d('deleteAllMessages: in cache: ${removedMessages.length}') ..d('size after deletion: $size'); notifyListeners(); final results = await futureResults; final parent = _parentMessageSource; if (parent != null) { for (final removedMessage in removedMessages) { final mime = removedMessage.mimeMessage; parent.removeMime(mime, getMimeSource(removedMessage)); } } return results; } @override Future<bool> markAllMessagesSeen(bool seen) async { cache.markAllMessageSeen(seen); await mimeSource.storeAll( [MessageFlags.seen], action: seen ? StoreAction.add : StoreAction.remove, ); return true; } @override bool get shouldBlockImages => mimeSource.shouldBlockImages; @override bool get isJunk => mimeSource.isJunk; @override bool get isArchive => mimeSource.isArchive; @override bool get isTrash => mimeSource.isTrash; @override bool get isSent => mimeSource.isSent; @override bool get supportsMessageFolders => mimeSource.supportsMessageFolders; @override bool get supportsSearching => mimeSource.supportsSearching; @override MessageSource search(AppLocalizations localizations, MailSearch search) { final searchSource = mimeSource.search(search); return MailboxMessageSource.fromMimeSource( searchSource, search.query, mailbox, account: account, parent: this, isSearch: true, ); } @override AsyncMimeSource? getMimeSource(Message message) => mimeSource; @override void clear() { cache.clear(); mimeSource.clear(); } @override void onMailCacheInvalidated(AsyncMimeSource source) { cache.clear(); notifyListeners(); } @override Future<Message> loadSingleMessage( MailNotificationPayload payload, ) async { final payloadMime = MimeMessage() ..sequenceId = payload.sequenceId ..uid = payload.uid; final mime = await mimeSource.mailClient.fetchMessageContents(payloadMime); final source = SingleMessageSource(this, account: account); final message = Message(mime, source, 0); source.singleMessage = message; return message; } } class _MultipleMessageSourceId { const _MultipleMessageSourceId(this.source, this.index); final AsyncMimeSource source; final int index; } /// Provides a unified source of several messages sources. /// Each message is ordered by date class MultipleMessageSource extends MessageSource { /// Creates a new [MultipleMessageSource] MultipleMessageSource( this.mimeSources, String name, this.flag, { required this.account, super.parent, super.isSearch, }) { for (final s in mimeSources) { s.addSubscriber(this); _multipleMimeSources.add(_MultipleMimeSource(s)); } _name = name; _description = mimeSources.map((s) => s.mailClient.account.name).join(', '); } @override final UnifiedAccount account; @override Future<void> init() async { final futures = mimeSources.map((source) => source.init()); await Future.wait(futures); supportsDeleteAll = mimeSources.any((s) => s.supportsDeleteAll); } /// The integrated mime sources final List<AsyncMimeSource> mimeSources; final _multipleMimeSources = <_MultipleMimeSource>[]; /// The identity flag of the mailbox MailboxFlag flag; final _indicesCache = <_MultipleMessageSourceId>[]; @override int get size { var complete = 0; for (final s in mimeSources) { complete += s.size; } //print('MultipleMessageSource.size: $complete'); return complete; } @override void dispose() { for (final s in mimeSources) { s ..removeSubscriber(this) ..dispose(); } super.dispose(); } Future<Message> _next(int index) async { final previousCall = index == 0 ? null : _nextCalls[index - 1]; if (previousCall != null) { // ensure that messages are retrieved sequentially await previousCall; } _MultipleMimeSourceMessage? newestMessage; final futures = _multipleMimeSources.map((source) => source.peek()); final sourceMessages = await Future.wait(futures); DateTime? newestTime; for (final sourceMessage in sourceMessages) { if (sourceMessage != null) { var date = sourceMessage.mimeMessage.decodeDate(); if (date == null) { date = DateTime.now(); if (kDebugMode) { print('unable to decode date for $index on ' '${sourceMessage.source.mimeSource.mailClient.account.name} ' 'message is empty: ${sourceMessage.mimeMessage.isEmpty}.'); } } if (newestTime == null || date.isAfter(newestTime)) { newestMessage = sourceMessage; newestTime = date; } } } if (newestMessage == null) { throw Exception('Unable to get next message for index $index'); } newestMessage.source.pop(); // newestSource._currentIndex could have changed in the meantime _indicesCache.add( _MultipleMessageSourceId( newestMessage.source.mimeSource, newestMessage.index, ), ); final message = _UnifiedMessage( newestMessage.mimeMessage, this, index, newestMessage.source.mimeSource, ); return message; } @override Future<Message> loadMessage(int index) async { if (index < _indicesCache.length) { final id = _indicesCache[index]; final mime = await id.source.getMessage(id.index); return _UnifiedMessage(mime, this, index, id.source); } int diff = index - _indicesCache.length; while (diff > 0) { final sourceIndex = index - diff; await getMessageAt(sourceIndex); diff--; } var nextCall = _nextCalls[index]; if (nextCall == null) { nextCall = _next(index); _nextCalls[index] = nextCall; } final nextMessage = await nextCall; await _nextCalls.remove(index); return nextMessage; } final _nextCalls = <int, Future<Message>>{}; @override bool removeFromCache(Message message, {bool notify = true}) { _indicesCache.removeAt(message.sourceIndex); return super.removeFromCache(message, notify: notify); } @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) async { final removedMessages = cache.getAllCachedEntries(); cache.clear(); _indicesCache.clear(); final futures = <Future<List<DeleteResult>>>[]; for (final multipleMimeSource in _multipleMimeSources) { futures.add(multipleMimeSource.deleteAllMessages(expunge: expunge)); } notifyListeners(); final parent = _parentMessageSource; if (parent != null) { for (final removedMessage in removedMessages) { parent.removeMime( removedMessage.mimeMessage, getMimeSource(removedMessage), ); } } final futureResults = await Future.wait(futures); final results = <DeleteResult>[]; futureResults.forEach(results.addAll); return results; } @override AsyncMimeSource getMimeSource(Message message) { if (message is _UnifiedMessage) { return message.mimeSource; } logger.e( 'Unable to retrieve mime source for ${message.runtimeType} / $message', ); return mimeSources.first; } @override Message createMessage( MimeMessage mime, AsyncMimeSource mimeSource, int index, ) => _UnifiedMessage(mime, this, index, mimeSource); @override bool get shouldBlockImages => mimeSources.any((source) => source.shouldBlockImages); @override bool get isJunk => mimeSources.every((source) => source.isJunk); @override bool get supportsMessageFolders => mimeSources.every((source) => source.supportsMessageFolders); @override bool get isArchive => mimeSources.every((source) => source.isArchive); @override bool get isTrash => mimeSources.every((source) => source.isTrash); @override bool get isSent => mimeSources.every((source) => source.isSent); @override bool get supportsSearching => mimeSources.any((source) => source.supportsSearching); @override MessageSource search(AppLocalizations localizations, MailSearch search) { final searchMimeSources = mimeSources .where((source) => source.supportsSearching) .map((source) => source.search(search)) .toList(); final searchMessageSource = MultipleMessageSource( searchMimeSources, localizations.searchQueryTitle(search.query), flag, account: account, parent: this, isSearch: true, ).._description = localizations.searchQueryDescription(name ?? ''); return searchMessageSource; } @override Future<void> markAllMessagesSeen(bool seen) async { cache.markAllMessageSeen(seen); final futures = <Future>[]; for (final mimeSource in mimeSources) { futures.add(mimeSource.storeAll([MessageFlags.seen])); } await Future.wait(futures); } @override void insertIntoCache(int index, Message message) { final mimeSource = getMimeSource(message); _indicesCache.insert(index, _MultipleMessageSourceId(mimeSource, index)); final multipleSource = _multipleMimeSources .firstWhereOrNull((element) => element.mimeSource == mimeSource); multipleSource?.onMailArrived(); for (var i = index + 1; i < _indicesCache.length; i++) { final id = _indicesCache[i]; if (id.source == mimeSource) { _indicesCache[i] = _MultipleMessageSourceId(mimeSource, id.index + 1); } } super.insertIntoCache(index, message); } @override void onMailArrived( MimeMessage mime, AsyncMimeSource source, { int index = 0, }) { // find out index: final mimeDate = mime.decodeDate() ?? DateTime.now(); var msgIndex = 0; while (cache[msgIndex] != null && (cache[msgIndex]?.mimeMessage.decodeDate()?.isAfter(mimeDate) ?? false)) { msgIndex++; } super.onMailArrived(mime, source, index: msgIndex); } @override void onMailCacheInvalidated(AsyncMimeSource source) { _indicesCache.clear(); _nextCalls.clear(); cache.clear(); for (final multipleSource in _multipleMimeSources) { multipleSource.onMailCacheInvalidated(); } notifyListeners(); } @override void clear() { _indicesCache.clear(); _nextCalls.clear(); for (final multipleSource in _multipleMimeSources) { multipleSource.clear(); } } } class _UnifiedMessage extends Message { _UnifiedMessage( super.mimeMessage, super.source, super.sourceIndex, this.mimeSource, ); final AsyncMimeSource mimeSource; } class _MultipleMimeSourceMessage { const _MultipleMimeSourceMessage(this.index, this.source, this.mimeMessage); final int index; final _MultipleMimeSource source; final MimeMessage mimeMessage; } class _MultipleMimeSource { _MultipleMimeSource(this.mimeSource); final AsyncMimeSource mimeSource; int _currentIndex = 0; _MultipleMimeSourceMessage? _currentMessage; Future<_MultipleMimeSourceMessage?> peek() async => _currentMessage ??= await _next(); void pop() { _currentMessage = null; } Future<_MultipleMimeSourceMessage?> _next() async { final index = _currentIndex; if (index >= mimeSource.size) { return null; } _currentIndex++; final mime = await mimeSource.getMessage(index); return _MultipleMimeSourceMessage(index, this, mime); } void clear() { _currentIndex = 0; _currentMessage = null; mimeSource.clear(); } Future<List<DeleteResult>> deleteAllMessages({required bool expunge}) { if (mimeSource.supportsDeleteAll) { _currentIndex = 0; _currentMessage = null; return mimeSource.deleteAllMessages(expunge: expunge); } return Future.value([]); } void onMailCacheInvalidated() { _currentIndex = 0; _currentMessage = null; } void onMailArrived() { _currentIndex++; } } class SingleMessageSource extends MessageSource { SingleMessageSource(MessageSource? parent, {required this.account}) : super(parent: parent); Message? singleMessage; @override final Account account; @override Future<Message> loadMessage(int index) => Future.value(singleMessage); @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) { throw UnimplementedError(); } @override Future<void> init() => Future.value(); @override bool get isArchive => false; @override bool get isJunk => false; @override bool get isTrash => false; @override bool get isSent => false; @override MessageSource search(AppLocalizations localizations, MailSearch search) { throw UnimplementedError(); } @override bool get shouldBlockImages => false; @override int get size => 1; @override bool get supportsMessageFolders => _parentMessageSource?.supportsMessageFolders ?? false; @override bool get supportsSearching => false; @override AsyncMimeSource? getMimeSource(Message message) => _parentMessageSource?.getMimeSource(message); @override Future<void> markAllMessagesSeen(bool seen) => Future.value(); @override void clear() { // nothing to implement } @override void onMailCacheInvalidated(AsyncMimeSource source) { // TODO(RV): implement onMailCacheInvalidated } } class ListMessageSource extends MessageSource { ListMessageSource( MessageSource parent, ) : account = parent.account, super(parent: parent); late List<Message> messages; @override final Account account; void initWithMimeMessages( List<MimeMessage> mimeMessages, { bool reverse = true, }) { var result = mimeMessages .mapIndexed((index, mime) => Message(mime, this, index)) .toList(); if (reverse) { result = result.reversed.toList(); } messages = result; } @override Future<Message> loadMessage(int index) => Future.value(messages[index]); @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) { throw UnimplementedError(); } @override Future<void> init() => Future.value(); @override bool get isArchive => false; @override bool get isJunk => false; @override bool get isTrash => false; @override bool get isSent => false; @override MessageSource search(AppLocalizations localizations, MailSearch search) { throw UnimplementedError(); } @override bool get shouldBlockImages => false; @override int get size => messages.length; @override bool get supportsMessageFolders => false; @override bool get supportsSearching => false; @override AsyncMimeSource? getMimeSource(Message message) => _parentMessageSource?.getMimeSource(message); @override Future<void> markAllMessagesSeen(bool seen) => Future.value(); @override void clear() { messages.clear(); } @override void onMailCacheInvalidated(AsyncMimeSource source) { // TODO(RV): implement onMailCacheInvalidated } } // class ThreadedMailboxMessageSource extends MailboxMessageSource { // ThreadedMailboxMessageSource(Mailbox mailbox, MailClient mailClient) // : super.fromMimeSource(ThreadedMimeSource(mailbox, mailClient), // mailClient.account.email, mailbox?.name) { // _mimeSource.addSubscriber(this); // } // } extension _ExtensionsOnMessageIndexedCache on IndexedCache<Message> { Message? getWithMime(MimeMessage mime, AsyncMimeSource? mimeSource) { final guid = mime.guid; if (guid != null) { return firstWhereOrNull( (msg) => msg.mimeMessage.guid == guid, ); } final sequenceId = mime.sequenceId; if (sequenceId != null) { return firstWhereOrNull( (msg) => msg.mimeMessage.sequenceId == sequenceId && msg.source.getMimeSource(msg) == mimeSource, ); } return null; } // Message? getWithSourceIndex(int sourceIndex, MailClient mailClient) => // firstWhereOrNull((msg) => // msg.mailClient == mailClient && msg.sourceIndex == sourceIndex); void markAllMessageSeen(bool seen) { final messages = getAllCachedEntries(); for (final message in messages) { message.isSeen = seen; } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/mail_operation.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'mail_operation.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** StoreFlagsOperation _$StoreFlagsOperationFromJson(Map<String, dynamic> json) => StoreFlagsOperation( flags: (json['flags'] as List<dynamic>).map((e) => e as String).toList(), sequence: MessageSequence.fromJson(json['sequence'] as Map<String, dynamic>), ); Map<String, dynamic> _$StoreFlagsOperationToJson( StoreFlagsOperation instance) => <String, dynamic>{ 'flags': instance.flags, 'sequence': instance.sequence, };
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/offline_mime_storage_factory.dart
import 'package:enough_mail/enough_mail.dart'; import 'hive/hive.dart'; import 'offline_mime_storage.dart'; /// Provides access to storage facilities class OfflineMimeStorageFactory { const OfflineMimeStorageFactory(); Future<void> init() => HiveMailboxMimeStorage.initGlobal(); OfflineMimeStorage getMailboxStorage({ required MailAccount mailAccount, required Mailbox mailbox, }) => HiveMailboxMimeStorage(mailAccount: mailAccount, mailbox: mailbox); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/swipe.dart
import 'package:flutter/material.dart'; import '../localization/app_localizations.g.dart'; import '../settings/theme/icon_service.dart'; enum SwipeAction { markRead, archive, markJunk, delete, flag, //move (later) } extension SwipeExtension on SwipeAction { Color get colorBackground { switch (this) { case SwipeAction.markRead: return Colors.blue[200] ?? Colors.lightBlue; case SwipeAction.archive: return Colors.amber[200] ?? Colors.amber; case SwipeAction.markJunk: return Colors.red[200] ?? Colors.orangeAccent; case SwipeAction.delete: return Colors.red[600] ?? Colors.red; case SwipeAction.flag: return Colors.lime[600] ?? Colors.lime; } } Color get colorForeground { switch (this) { case SwipeAction.markRead: return Colors.black; case SwipeAction.archive: return Colors.black; case SwipeAction.markJunk: return Colors.black; case SwipeAction.delete: return Colors.white; case SwipeAction.flag: return Colors.black; } } Color get colorIcon { switch (this) { case SwipeAction.markRead: return Colors.blue[900] ?? Colors.blue; case SwipeAction.archive: return Colors.amber[900] ?? Colors.amber; case SwipeAction.markJunk: return Colors.red[900] ?? Colors.red; case SwipeAction.delete: return Colors.white; case SwipeAction.flag: return Colors.lime[900] ?? Colors.lime; } } Brightness get brightness { switch (this) { case SwipeAction.markRead: return Brightness.light; case SwipeAction.archive: return Brightness.light; case SwipeAction.markJunk: return Brightness.light; case SwipeAction.delete: return Brightness.dark; case SwipeAction.flag: return Brightness.light; } } /// Icon of the action IconData get icon { final iconService = IconService.instance; switch (this) { case SwipeAction.markRead: return iconService.messageIsNotSeen; case SwipeAction.archive: return iconService.messageActionArchive; case SwipeAction.markJunk: return iconService.messageActionMoveToJunk; case SwipeAction.delete: return iconService.messageActionDelete; case SwipeAction.flag: return iconService.messageIsNotFlagged; } } /// localized name of the action String name(AppLocalizations localizations) { switch (this) { case SwipeAction.markRead: return localizations.swipeActionToggleRead; case SwipeAction.archive: return localizations.swipeActionArchive; case SwipeAction.markJunk: return localizations.swipeActionMarkJunk; case SwipeAction.delete: return localizations.swipeActionDelete; case SwipeAction.flag: return localizations.swipeActionFlag; } } /// The threshold in percent when the action is triggered double get dismissThreshold { switch (this) { case SwipeAction.markRead: return 0.3; case SwipeAction.archive: return 0.5; case SwipeAction.markJunk: return 0.5; case SwipeAction.delete: return 0.5; case SwipeAction.flag: return 0.3; } } /// Does this action move the message away from the current list? bool get isMessageMoving { switch (this) { case SwipeAction.markRead: return false; case SwipeAction.archive: return true; case SwipeAction.markJunk: return true; case SwipeAction.delete: return true; case SwipeAction.flag: return false; } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/offline_mime_source.dart
import 'dart:async'; import 'package:enough_mail/enough_mail.dart'; import 'async_mime_source.dart'; import 'offline_mime_storage.dart'; /// Provides access to messages that have been stored offline class OfflineMailboxMimeSource extends PagedCachedMimeSource { /// Creates a new [OfflineMailboxMimeSource] OfflineMailboxMimeSource({ required MailAccount mailAccount, required this.mailbox, required PagedCachedMimeSource onlineMimeSource, required OfflineMimeStorage storage, }) : _mailAccount = mailAccount, _onlineMimeSource = onlineMimeSource, _storage = storage; final MailAccount _mailAccount; @override final Mailbox mailbox; final PagedCachedMimeSource _onlineMimeSource; final OfflineMimeStorage _storage; late StreamSubscription<MailLoadEvent> _mailLoadEventSubscription; late StreamSubscription<MailVanishedEvent> _mailVanishedEventSubscription; late StreamSubscription<MailUpdateEvent> _mailUpdatedEventSubscription; late StreamSubscription<MailConnectionReEstablishedEvent> _mailReconnectedEventSubscription; @override Future<void> init() async { _subscribeEvents(); final futures = [_onlineMimeSource.init(), _storage.init()]; await Future.wait(futures); } @override void dispose() { _unsubscribeEvents(); } @override Future<MimeMessage> fetchMessageContents( MimeMessage message, { int? maxSize, bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, Duration? responseTimeout, }) async { final contents = await _storage.fetchMessageContents( message, markAsSeen: markAsSeen, includedInlineTypes: includedInlineTypes, ); if (contents != null) { return contents; } final onlineContents = await _onlineMimeSource.fetchMessageContents( message, maxSize: maxSize, markAsSeen: markAsSeen, includedInlineTypes: includedInlineTypes, responseTimeout: responseTimeout, ); await _storage.saveMessageContents(onlineContents); return onlineContents; } @override Future<MimePart> fetchMessagePart( MimeMessage message, { required String fetchId, Duration? responseTimeout, }) => _onlineMimeSource.fetchMessagePart( message, fetchId: fetchId, responseTimeout: responseTimeout, ); @override Future<void> sendMessage( MimeMessage message, { MailAddress? from, bool appendToSent = true, Mailbox? sentMailbox, bool use8BitEncoding = false, List<MailAddress>? recipients, }) => _onlineMimeSource.sendMessage( message, from: from, appendToSent: appendToSent, sentMailbox: sentMailbox, use8BitEncoding: use8BitEncoding, recipients: recipients, ); @override Future<void> handleOnMessageArrived(int index, MimeMessage message) => Future.wait([ _storage.saveMessageEnvelopes([message]), if (message.mimeData != null) _storage.saveMessageContents(message), ]); @override Future<void> handleOnMessagesVanished(List<MimeMessage> messages) => Future.wait( messages.map(_storage.deleteMessage), ); @override bool get isArchive => mailbox.isArchive; @override bool get isInbox => mailbox.isInbox; @override bool get isJunk => mailbox.isJunk; @override bool get isSent => mailbox.isSent; @override bool get isTrash => mailbox.isTrash; @override Future<List<MimeMessage>> loadMessages(MessageSequence sequence) async { final messages = await _storage.loadMessageEnvelopes(sequence); if (messages != null) { return messages; } final onlineMessages = await _onlineMimeSource.loadMessages(sequence); await _storage.saveMessageEnvelopes(onlineMessages); return onlineMessages; } @override MailClient get mailClient => _onlineMimeSource.mailClient; @override Future<MoveResult> moveMessages( List<MimeMessage> messages, Mailbox targetMailbox, ) async { // TODO(RV): this and most other offline ops should be done with a queue // Some ops can be done offline and an later online, e.g. store flags // Some ops must update their offline part after having finished it online, // e.g. move, append - because the UID and sequence ID can only be known // after storing it online // What happens with ops that go back and forth, e.g. delete, then un-delete // or archive message and then delete message while being offline? final result = await _onlineMimeSource.moveMessages(messages, targetMailbox); await _storage.moveMessages(messages, targetMailbox); return result; } @override Future<MoveResult> moveMessagesToFlag( List<MimeMessage> messages, MailboxFlag targetMailboxFlag, ) { // TODO(RV): implement moveMessagesToFlag throw UnimplementedError(); } @override Future<MoveResult> undoMoveMessages(MoveResult moveResult) { // TODO(RV): implement undoMoveMessages throw UnimplementedError(); } @override Future<List<DeleteResult>> deleteAllMessages({bool expunge = false}) { // TODO(RV): implement deleteAllMessages throw UnimplementedError(); } @override Future<DeleteResult> deleteMessages(List<MimeMessage> messages) { // TODO(RV): implement deleteMessages throw UnimplementedError(); } @override Future<DeleteResult> undoDeleteMessages(DeleteResult deleteResult) { // TODO(RV): implement undoDeleteMessages throw UnimplementedError(); } @override String get name => _onlineMimeSource.name; @override AsyncMimeSource search(MailSearch search) { // TODO(RV): implement search throw UnimplementedError(); } @override int get size => mailbox.messagesExists; @override Future<void> store( List<MimeMessage> messages, List<String> flags, { StoreAction action = StoreAction.add, }) => Future.wait( [ _storage.saveMessageEnvelopes(messages), _onlineMimeSource.store( messages, flags, action: action, ), ], ); @override Future<void> storeAll( List<String> flags, { StoreAction action = StoreAction.add, }) { // TODO(RV): implement storeAll throw UnimplementedError(); } @override bool get supportsDeleteAll => _onlineMimeSource.supportsDeleteAll; @override bool get supportsMessageFolders => _onlineMimeSource.supportsMessageFolders; @override bool get supportsSearching => _onlineMimeSource.supportsSearching; void _subscribeEvents() { _mailLoadEventSubscription = mailClient.eventBus.on<MailLoadEvent>().listen((event) { if (event.mailClient == mailClient) { onMessageArrived(event.message); } }); _mailVanishedEventSubscription = mailClient.eventBus.on<MailVanishedEvent>().listen((event) { final sequence = event.sequence; if (sequence != null && event.mailClient == mailClient) { onMessagesVanished(sequence); } }); _mailUpdatedEventSubscription = mailClient.eventBus.on<MailUpdateEvent>().listen((event) { if (event.mailClient == mailClient) { onMessageFlagsUpdated(event.message); } }); // _mailReconnectedEventSubscription = mailClient.eventBus // .on<MailConnectionReEstablishedEvent>() // .listen(_onMailReconnected); } void _unsubscribeEvents() { _mailLoadEventSubscription.cancel(); _mailVanishedEventSubscription.cancel(); _mailUpdatedEventSubscription.cancel(); _mailReconnectedEventSubscription.cancel(); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/mail_operation.dart
import 'dart:convert'; import 'package:enough_mail/enough_mail.dart'; import 'package:json_annotation/json_annotation.dart'; import 'hive/hive_mime_storage.dart'; import 'offline_mime_storage.dart'; part 'mail_operation.g.dart'; /// The type of a mail operation enum MailOperationType { /// update flags like `/Seen` storeFlags, moveToFlag, moveToFolder, } /// Defines the API for a mail operation abstract class MailOperation { /// Creates a new mail operation MailOperation(this.type); /// The type of the operation /// /// Note that new types need to be registered with the [MailOperationQueue] final MailOperationType type; /// Executes this mail operation Future<void> execute(MailClient mailClient, OfflineMimeStorage storage); } /// Works on [MailOperation]s and allows to queue them. class MailOperationQueue { MailOperationQueue._(this._queue); static const String _keyQueue = 'mailOperationsQueue'; final List<_QueuedMailOperation> _queue; /// Adds the mail operation at the beginning of this queue void prepend(MailOperation op, String email) { _queue.insert(0, _QueuedMailOperation(op, email)); _storeQueue(); } /// Inserts the mail operation at the beginning of this queue void append(MailOperation op, String email) { _queue.add(_QueuedMailOperation(op, email)); _storeQueue(); } Future<void> _storeQueue() async { final list = _queue.map((e) => e.toJson()).toList(); final value = json.encode(list); await TextHiveStorage.instance.save(_keyQueue, value); } /// Loads the [MailOperationQueue] static Future<MailOperationQueue> loadQueue() async { final savedData = await TextHiveStorage.instance.load(_keyQueue); if (savedData == null) { return MailOperationQueue._(<_QueuedMailOperation>[]); } final data = json.decode(savedData) as List; final entries = data .map( // ignore: unnecessary_lambdas (json) => _QueuedMailOperation.fromJson(json), ) .toList(); return MailOperationQueue._(entries); } } class _QueuedMailOperation { _QueuedMailOperation(this.operation, this.email); factory _QueuedMailOperation.fromJson(Map<String, dynamic> input) { final String email = input['email']!; final type = MailOperationType.values[input['typeIndex']!]; final Map<String, dynamic> data = input['operation']!; final MailOperation operation; switch (type) { case MailOperationType.storeFlags: operation = StoreFlagsOperation.fromJson(data); break; // case MailOperationType.moveToFlag: // TODO(RV): Handle this case. // break; // case MailOperationType.moveToFolder: // TODO(RV): Handle this case. // break; default: throw FormatException('Unsupported type $type'); } return _QueuedMailOperation(operation, email); } final MailOperation operation; final String email; Map<String, dynamic> toJson() => { 'email': email, 'typeIndex': operation.type.index, //'operation': operation.toJson(), }; } /// An operation to store flags @JsonSerializable() class StoreFlagsOperation extends MailOperation { /// Creates a new [StoreFlagsOperation] StoreFlagsOperation({ required this.flags, required this.sequence, }) : super(MailOperationType.storeFlags); // De-serialized the JSON to a store flags operation factory StoreFlagsOperation.fromJson(Map<String, dynamic> json) => _$StoreFlagsOperationFromJson(json); /// The flags to store final List<String> flags; /// The sequence of messages final MessageSequence sequence; /// Serializes the data to JSON Map<String, dynamic> toJson() => _$StoreFlagsOperationToJson(this); @override Future<void> execute(MailClient mailClient, OfflineMimeStorage storage) { // TODO(RV): implement execute throw UnimplementedError(); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/message_date_section.dart
import '../util/date_helper.dart'; class MessageDateSection { MessageDateSection(this.range, this.date, this.sourceStartIndex); final DateSectionRange range; final DateTime date; final int sourceStartIndex; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/message.dart
import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'package:url_launcher/url_launcher.dart' as url_launcher; import '../account/model.dart'; import '../logger.dart'; import 'message_source.dart'; class Message extends ChangeNotifier { Message(this.mimeMessage, this.source, this.sourceIndex); Message.embedded(this.mimeMessage, Message parent) : source = SingleMessageSource( parent.source, account: parent.source.account, ), sourceIndex = 0 { (source as SingleMessageSource).singleMessage = this; isEmbedded = true; } static const String keywordFlagUnsubscribed = r'$Unsubscribed'; MimeMessage mimeMessage; int sourceIndex; final MessageSource source; bool _isSelected = false; bool get isSelected => _isSelected; List<ContentInfo>? _attachments; List<ContentInfo> get attachments { var infos = _attachments; if (infos == null) { infos = mimeMessage.findContentInfo(); final inlineAttachments = mimeMessage .findContentInfo(disposition: ContentDisposition.inline) .where((info) => info.fetchId.isNotEmpty && !(info.isText || info.isImage || info.mediaType?.sub == MediaSubtype.messageDispositionNotification)); infos.addAll(inlineAttachments); _attachments = infos; } return infos; } Account get account => source.account; set isSelected(bool value) { if (value != _isSelected) { _isSelected = value; notifyListeners(); } } bool isEmbedded = false; bool get hasNext => sourceIndex < source.size; Future<Message?> get next => source.next(this); bool get hasPrevious => sourceIndex > 0; Future<Message?> get previous => source.previous(this); bool get isSeen => mimeMessage.isSeen; set isSeen(bool value) { if (value != mimeMessage.isSeen) { mimeMessage.isSeen = value; notifyListeners(); } } bool get isFlagged => mimeMessage.isFlagged; set isFlagged(bool value) { if (value != mimeMessage.isFlagged) { mimeMessage.isFlagged = value; notifyListeners(); } } bool get isAnswered => mimeMessage.isAnswered; set isAnswered(bool value) { if (value != mimeMessage.isAnswered) { mimeMessage.isAnswered = value; notifyListeners(); } } bool get isForwarded => mimeMessage.isForwarded; set isForwarded(bool value) { if (value != mimeMessage.isForwarded) { mimeMessage.isForwarded = value; notifyListeners(); } } bool get isDeleted => mimeMessage.isDeleted; set isDeleted(bool value) { if (value != mimeMessage.isDeleted) { mimeMessage.isDeleted = value; notifyListeners(); } } bool get isMdnSent => mimeMessage.isReadReceiptSent; set isMdnSent(bool value) { if (value != mimeMessage.isReadReceiptSent) { mimeMessage.isReadReceiptSent = value; notifyListeners(); } } bool get isNewsLetter => mimeMessage.isNewsletter; bool get isNewsLetterSubscribable => mimeMessage.isNewsLetterSubscribable; bool get isNewsletterUnsubscribed => mimeMessage.hasFlag(keywordFlagUnsubscribed); set isNewsletterUnsubscribed(bool value) { mimeMessage.setFlag(keywordFlagUnsubscribed, value); notifyListeners(); } bool get hasAttachment { final mime = mimeMessage; final size = mime.size; // when only the envelope is downloaded, the content-type header ergo // mediaType is not yet available return mime.hasAttachments() || (mime.mimeData == null && mime.body == null && size != null && size > 256 * 1024); } void updateFlags(List<String>? flags) { mimeMessage.flags = flags; notifyListeners(); } void updateMime(MimeMessage mime) { mimeMessage = mime; _attachments = null; notifyListeners(); } void toggleSelected() { isSelected = !_isSelected; } @override String toString() => '${account.name}[$sourceIndex]=$mimeMessage'; } extension NewsLetter on MimeMessage { bool get isEmpty => mimeData == null && envelope == null && body == null; /// Checks if this is a newsletter with a `list-unsubscribe` header. bool get isNewsletter => hasHeader('list-unsubscribe'); /// Checks if this is a newsletter with a `list-subscribe` header. bool get isNewsLetterSubscribable => hasHeader('list-subscribe'); /// Retrieves the List-Unsubscribe URIs, if present List<Uri>? decodeListUnsubscribeUris() => _decodeUris('list-unsubscribe'); List<Uri>? decodeListSubscribeUris() => _decodeUris('list-subscribe'); String? decodeListName() { final listPost = decodeHeaderValue('list-post'); if (listPost != null) { // typically only mailing lists that allow posting have a // human understandable List-ID header: final id = decodeHeaderValue('list-id'); if (id != null && id.isNotEmpty) { return id; } final startIndex = listPost.indexOf('<mailto:'); if (startIndex != -1) { final endIndex = listPost.indexOf('>', startIndex + '<mailto:'.length); if (endIndex != -1) { return listPost.substring(startIndex + '<mailto:'.length, endIndex); } } } final sender = decodeSender(); if (sender.isNotEmpty) { return sender.first.toString(); } return null; } List<Uri>? _decodeUris(final String name) { final value = getHeaderValue(name); if (value == null) { return null; } // TODO(RV): allow comments in / before URIs, e.g. "(send a mail to unsubscribe) <mailto:unsubscribe@list.org>" final uris = <Uri>[]; final parts = value.split('>'); for (var part in parts) { part = part.trimLeft(); if (part.startsWith(',')) { part = part.substring(1).trimLeft(); } if (part.startsWith('<')) { part = part.substring(1); } if (part.isNotEmpty) { final uri = Uri.tryParse(part); if (uri == null) { logger.e('Invalid $name $value: unable to pars URI $part'); } else { uris.add(uri); } } } return uris; } bool hasListUnsubscribePostHeader() => hasHeader('list-unsubscribe-post'); Future<bool> unsubscribe(MailClient client) async { final uris = decodeListUnsubscribeUris(); if (uris == null) { return false; } final httpUri = uris.firstWhereOrNull( (uri) => uri.scheme.toLowerCase() == 'https', ) ?? uris.firstWhereOrNull( (uri) => uri.scheme.toLowerCase() == 'http', ); // unsubscribe via one click POST request: https://tools.ietf.org/html/rfc8058 if (hasListUnsubscribePostHeader() && httpUri != null) { final response = await unsubscribeWithOneClick(httpUri); if (response.statusCode == 200) { return true; } } // unsubscribe via generated mail: final mailtoUri = uris.firstWhereOrNull( (uri) => uri.scheme.toLowerCase() == 'mailto', ); if (mailtoUri != null) { await sendMailto(mailtoUri, client, 'unsubscribe'); return true; } // manually open unsubscribe web page: if (httpUri != null) { return url_launcher.launchUrl(httpUri); } return false; } Future<bool> subscribe(MailClient client) async { final uris = decodeListSubscribeUris(); if (uris == null) { return false; } // subscribe via generated mail: final mailtoUri = uris.firstWhereOrNull( (uri) => uri.scheme.toLowerCase() == 'mailto', ); if (mailtoUri != null) { await sendMailto(mailtoUri, client, 'subscribe'); return true; } // manually open subscribe web page: final httpUri = uris.firstWhereOrNull( (uri) => uri.scheme.toLowerCase() == 'https', ) ?? uris.firstWhereOrNull( (uri) => uri.scheme.toLowerCase() == 'http', ); if (httpUri != null) { return url_launcher.launchUrl(httpUri); } return false; } Future<http.StreamedResponse> unsubscribeWithOneClick(Uri uri) { final request = http.MultipartRequest('POST', uri) ..fields['List-Unsubscribe'] = 'One-Click'; return request.send(); } Future<void> sendMailto( Uri mailtoUri, MailClient client, String defaultSubject, ) { final account = client.account; var me = findRecipient( account.fromAddress, aliases: account.aliases, allowPlusAliases: account.supportsPlusAliases, ); me ??= account.fromAddress; final builder = MessageBuilder.prepareMailtoBasedMessage(mailtoUri, me) ..subject ??= defaultSubject ..text ??= defaultSubject; final message = builder.buildMimeMessage(); return client.sendMessage(message, appendToSent: false); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/search.dart
class Search {}
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/contact.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:json_annotation/json_annotation.dart'; part 'contact.g.dart'; @JsonSerializable() class Group { const Group({required this.name}); final String name; } @JsonSerializable() class Contact { const Contact({ required this.name, required this.mailAddresses, this.birthday, }); final String name; final List<MailAddress> mailAddresses; final DateTime? birthday; //phone numbers, profile photo(s), // TODO(RV): consider full vCard support }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/async_mime_source_factory.dart
import 'package:enough_mail/enough_mail.dart'; import 'async_mime_source.dart'; import 'offline_mime_source.dart'; import 'offline_mime_storage_factory.dart'; /// Creates [AsyncMimeSource] instances class AsyncMimeSourceFactory { /// Creates a new [AsyncMimeSourceFactory] /// /// Set [isOfflineModeSupported] to `true` const AsyncMimeSourceFactory({ required bool isOfflineModeSupported, OfflineMimeStorageFactory storageFactory = const OfflineMimeStorageFactory(), }) : _isOfflineModeSupported = isOfflineModeSupported, _storageFactory = storageFactory; /// Should the generated mime source support being used in offline mode? final bool _isOfflineModeSupported; final OfflineMimeStorageFactory _storageFactory; /// Creates a new mailbox-based mime source AsyncMimeSource createMailboxMimeSource( MailClient mailClient, Mailbox mailbox, ) { final onlineSource = AsyncMailboxMimeSource(mailbox, mailClient); if (_isOfflineModeSupported) { final storage = _storageFactory.getMailboxStorage( mailAccount: mailClient.account, mailbox: mailbox, ); return OfflineMailboxMimeSource( mailAccount: mailClient.account, mailbox: mailbox, onlineMimeSource: onlineSource, storage: storage, ); } return onlineSource; } Future<void> init() => _storageFactory.init(); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/models.dart
export '../settings/model.dart'; export 'async_mime_source.dart'; export 'compose_data.dart'; export 'contact.dart'; export 'date_sectioned_message_source.dart'; export 'message.dart'; export 'message_date_section.dart'; export 'message_source.dart'; export 'search.dart'; export 'sender.dart'; export 'swipe.dart'; export 'web_view_configuration.dart';
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/web_view_configuration.dart
class WebViewConfiguration { WebViewConfiguration(this.title, this.uri); final String? title; final Uri uri; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/models/contact.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'contact.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Group _$GroupFromJson(Map<String, dynamic> json) => Group( name: json['name'] as String, ); Map<String, dynamic> _$GroupToJson(Group instance) => <String, dynamic>{ 'name': instance.name, }; Contact _$ContactFromJson(Map<String, dynamic> json) => Contact( name: json['name'] as String, mailAddresses: (json['mailAddresses'] as List<dynamic>) .map((e) => MailAddress.fromJson(e as Map<String, dynamic>)) .toList(), birthday: json['birthday'] == null ? null : DateTime.parse(json['birthday'] as String), ); Map<String, dynamic> _$ContactToJson(Contact instance) => <String, dynamic>{ 'name': instance.name, 'mailAddresses': instance.mailAddresses, 'birthday': instance.birthday?.toIso8601String(), };
0
mirrored_repositories/enough_mail_app/lib/src/models
mirrored_repositories/enough_mail_app/lib/src/models/hive/hive_mime_storage.dart
import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:hive_flutter/hive_flutter.dart'; import '../../logger.dart'; import '../offline_mime_storage.dart'; part 'hive_mime_storage.g.dart'; /// A mime storage using Hive as its backend /// /// idea: /// use 2-3 structures for each mailbox: /// 1) list of SequenceId-UID-GUID elements - to be loaded when mailbox is /// opened, possibly along with envelope data of first page to speed up /// loading /// 2) possibly envelope data by GUID (contains flags, subject, senders, /// recipients, date, has-attachment, possibly message preview) /// 3) downloaded message data by GUID - this may not (yet) contain attachments /// /// new message: /// add to 1 (plus first page of envelope data) and 2 /// downloaded message: /// add to 3 /// delete message: /// remove from 1, 2 and 3 /// delete all messages: /// clear 1, 2 and 3 /// store/flag message: /// update 2 and 3 class HiveMailboxMimeStorage extends OfflineMimeStorage { HiveMailboxMimeStorage({ required MailAccount mailAccount, required Mailbox mailbox, }) : _mailAccount = mailAccount, _mailbox = mailbox, _boxNameIds = _getBoxName(mailAccount, mailbox, 'ids'), _boxNameEnvelopes = _getBoxName(mailAccount, mailbox, 'envelopes'), _boxNameFullMessages = _getBoxName(mailAccount, mailbox, 'full'); static const _keyMessageIds = 'ids'; final MailAccount _mailAccount; final Mailbox _mailbox; final String _boxNameIds; final String _boxNameEnvelopes; final String _boxNameFullMessages; late Box<List> _boxIds; late LazyBox<StorageMessageEnvelope> _boxEnvelopes; late LazyBox<String> _boxFullMessages; late List<StorageMessageId> _allMessageIds; static String _getBoxName( MailAccount mailAccount, Mailbox mailbox, String name, ) => '${mailAccount.email}_${mailbox.encodedPath.replaceAll('/', '_')}_$name'; static Future<void> initGlobal() async { Hive ..registerAdapter(StorageMessageIdAdapter()) ..registerAdapter(StorageMessageEnvelopeAdapter()); await Hive.initFlutter(); } @override Future<void> init() { Future<void> initIds() async { _boxIds = await Hive.openBox<List>(_boxNameIds); _allMessageIds = _boxIds.get(_keyMessageIds)?.cast<StorageMessageId>() ?? <StorageMessageId>[]; } Future<void> initEnvelopes() async { _boxEnvelopes = await Hive.openLazyBox<StorageMessageEnvelope>(_boxNameEnvelopes); } Future<void> initFullMessages() async { _boxFullMessages = await Hive.openLazyBox<String>(_boxNameFullMessages); } return Future.wait([initIds(), initEnvelopes(), initFullMessages()]); } @override Future<List<MimeMessage>?> loadMessageEnvelopes( MessageSequence sequence, ) async { logger.d('load offline message for ${_mailAccount.name}'); final ids = sequence.toList(_mailbox.messagesExists); final allIds = _allMessageIds; if (allIds.length < ids.length) { logger.d('${_mailAccount.name}: not enough ids (${allIds.length})'); return null; } final envelopes = <MimeMessage>[]; final isUid = sequence.isUidSequence; for (final id in ids) { final messageId = allIds.firstWhereOrNull((messageId) => isUid ? messageId.uid == id : messageId.sequenceId == id); if (messageId == null) { logger.d( '${_mailAccount.name}: ${isUid ? 'uid' : 'sequence-id'}' ' $id not found in allIds', ); return null; } final messageEnvelope = await _boxEnvelopes.get(messageId.guid); if (messageEnvelope == null) { logger.d( '${_mailAccount.name}: message data not found for ' 'guid ${messageId.guid} belonging to ' '${isUid ? 'uid' : 'sequence-id'} $id ', ); return null; } final mimeMessage = messageEnvelope.toMimeMessage(); envelopes.add(mimeMessage); } logger.d('${_mailAccount.name}: all messages loaded offline :-)'); return envelopes; } @override Future<void> saveMessageContents(MimeMessage mimeMessage) async { final data = mimeMessage.mimeData; final guid = mimeMessage.guid; if (data != null && guid != null) { await _boxFullMessages.put(guid, data.toString()); } } @override Future<void> saveMessageEnvelopes(List<MimeMessage> messages) async { final map = <int, StorageMessageEnvelope>{}; final allMessageIds = _allMessageIds; var addedMessageIds = 0; for (final message in messages) { final guid = message.guid; if (guid != null) { final existingMessageId = allMessageIds.firstWhereOrNull((id) => id.guid == guid); final sequenceId = message.sequenceId ?? 0; final uid = message.uid ?? 0; if (existingMessageId == null) { addedMessageIds++; final messageId = StorageMessageId(sequenceId: sequenceId, uid: uid, guid: guid); allMessageIds.add(messageId); } map[guid] = StorageMessageEnvelope.fromMessage( message: message, uid: uid, guid: guid, sequenceId: sequenceId, ); } } final futures = [ _boxEnvelopes.putAll(map), _boxIds.put(_keyMessageIds, allMessageIds), ]; logger.d( '${_mailAccount.name}: saved message envelopes :-) ' '(ids: $addedMessageIds (total: ${allMessageIds.length}) / ' 'envelopes: ${map.length})', ); await Future.wait(futures); } @override Future<MimeMessage?> fetchMessageContents( MimeMessage mimeMessage, { bool markAsSeen = false, List<MediaToptype>? includedInlineTypes, }) async { final guid = mimeMessage.guid; if (guid == null) { return null; } final existingContent = await _boxFullMessages.get(guid); if (existingContent == null) { return null; } return MimeMessage.parseFromText(existingContent); } @override Future<void> onAccountRemoved() { final futures = [ Hive.deleteBoxFromDisk(_boxNameIds), Hive.deleteBoxFromDisk(_boxNameEnvelopes), Hive.deleteBoxFromDisk(_boxNameFullMessages), ]; return Future.wait(futures); } @override Future<void> deleteMessage(MimeMessage message) { final guid = message.guid; if (guid == null) { return Future.value(); } logger.d('delete message with guid $guid from storage'); _allMessageIds.removeWhere((id) => id.guid == guid); return Future.wait([ _boxIds.put(_keyMessageIds, _allMessageIds), _boxEnvelopes.delete(guid), _boxFullMessages.delete(guid), ]); } @override Future<void> moveMessages(List<MimeMessage> messages, Mailbox targetMailbox) { // TODO(RV): implement moveMessages throw UnimplementedError(); } } /// Stores hive mail operations class TextHiveStorage { TextHiveStorage._(); /// Retrieves access to the text hive storage static TextHiveStorage get instance => _instance; static final TextHiveStorage _instance = TextHiveStorage._(); static const String _keyTextBox = '_texts'; Box<String>? _textBox; /// Stores the [value] /// /// Compare [load] Future<void> save(String key, String value) async { final box = _textBox ?? await Hive.openBox<String>(_keyTextBox); _textBox ??= box; await box.put(key, value); } /// Loads the value previously stored with [key]. /// /// Compare [save] Future<String?> load(String key) async { final box = _textBox ?? await Hive.openBox<String>(_keyTextBox); _textBox ??= box; return box.get(key); } } /// Contains the message IDs in a dense data structure @HiveType(typeId: 1) class StorageMessageId { /// Creates a new [StorageMessageId] const StorageMessageId({ required this.sequenceId, required this.uid, required this.guid, }); /// The sequence ID @HiveField(0) final int sequenceId; @HiveField(1) /// The folder unique ID final int uid; /// The globally unique ID @HiveField(2) final int guid; } /// Message envelope, UID, GUID and flags @HiveType(typeId: 2) class StorageMessageEnvelope { const StorageMessageEnvelope({ this.flags, required this.uid, required this.guid, required this.sequenceId, required this.sender, this.from, this.replyTo, this.to, this.cc, this.bcc, this.subject, this.date, this.messageId, this.inReplyTo, }); factory StorageMessageEnvelope.fromEnvelope({ required Envelope envelope, required int uid, required int guid, required int sequenceId, List<String>? flags, }) => StorageMessageEnvelope( uid: uid, guid: guid, sequenceId: sequenceId, sender: envelope.sender?.encode(), from: _mapAddresses(envelope.from), replyTo: _mapAddresses(envelope.replyTo), to: _mapAddresses(envelope.to), cc: _mapAddresses(envelope.cc), bcc: _mapAddresses(envelope.bcc), subject: envelope.subject, date: envelope.date, messageId: envelope.messageId, inReplyTo: envelope.inReplyTo, flags: flags, ); factory StorageMessageEnvelope.fromMessage({ required MimeMessage message, required int uid, required int guid, required int sequenceId, }) { final envelope = message.envelope; if (envelope != null) { return StorageMessageEnvelope.fromEnvelope( envelope: envelope, uid: uid, guid: guid, sequenceId: sequenceId, flags: message.flags, ); } return StorageMessageEnvelope( uid: uid, guid: guid, sequenceId: sequenceId, sender: message.sender?.encode(), from: _mapAddresses(message.from), replyTo: _mapAddresses(message.replyTo), to: _mapAddresses(message.to), cc: _mapAddresses(message.cc), bcc: _mapAddresses(message.bcc), subject: message.decodeSubject(), date: message.decodeDate(), messageId: message.getHeaderValue(MailConventions.headerMessageId), inReplyTo: message.getHeaderValue(MailConventions.headerInReplyTo), flags: message.flags, ); } static List<String>? _mapAddresses(List<MailAddress>? addresses) => addresses?.map((a) => a.encode()).toList(); @HiveField(0) final List<String>? flags; @HiveField(1) final int uid; @HiveField(2) final int guid; @HiveField(3) final int sequenceId; @HiveField(4) final String? sender; @HiveField(5) final List<String>? from; @HiveField(6) final List<String>? replyTo; @HiveField(7) final List<String>? to; @HiveField(8) final List<String>? cc; @HiveField(9) final List<String>? bcc; @HiveField(10) final String? subject; @HiveField(11) final DateTime? date; @HiveField(12) final String? messageId; @HiveField(13) final String? inReplyTo; MimeMessage toMimeMessage() => MimeMessage.fromEnvelope( toEnvelope(), uid: uid, guid: guid, sequenceId: sequenceId, flags: flags, ); Envelope toEnvelope() { List<MailAddress>? parseAddresses(List<String>? input) => input?.map(MailAddress.parse).toList(); MailAddress? parse(String? input) { if (input == null) { return null; } return MailAddress.parse(input); } return Envelope( date: date, subject: subject, sender: parse(sender), from: parseAddresses(from), replyTo: parseAddresses(replyTo), to: parseAddresses(to), cc: parseAddresses(cc), bcc: parseAddresses(cc), inReplyTo: inReplyTo, messageId: messageId, ); } }
0
mirrored_repositories/enough_mail_app/lib/src/models
mirrored_repositories/enough_mail_app/lib/src/models/hive/hive.dart
export 'hive_mime_storage.dart';
0
mirrored_repositories/enough_mail_app/lib/src/models
mirrored_repositories/enough_mail_app/lib/src/models/hive/hive_mime_storage.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'hive_mime_storage.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class StorageMessageIdAdapter extends TypeAdapter<StorageMessageId> { @override final int typeId = 1; @override StorageMessageId read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return StorageMessageId( sequenceId: fields[0] as int, uid: fields[1] as int, guid: fields[2] as int, ); } @override void write(BinaryWriter writer, StorageMessageId obj) { writer ..writeByte(3) ..writeByte(0) ..write(obj.sequenceId) ..writeByte(1) ..write(obj.uid) ..writeByte(2) ..write(obj.guid); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is StorageMessageIdAdapter && runtimeType == other.runtimeType && typeId == other.typeId; } class StorageMessageEnvelopeAdapter extends TypeAdapter<StorageMessageEnvelope> { @override final int typeId = 2; @override StorageMessageEnvelope read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return StorageMessageEnvelope( flags: (fields[0] as List?)?.cast<String>(), uid: fields[1] as int, guid: fields[2] as int, sequenceId: fields[3] as int, sender: fields[4] as String?, from: (fields[5] as List?)?.cast<String>(), replyTo: (fields[6] as List?)?.cast<String>(), to: (fields[7] as List?)?.cast<String>(), cc: (fields[8] as List?)?.cast<String>(), bcc: (fields[9] as List?)?.cast<String>(), subject: fields[10] as String?, date: fields[11] as DateTime?, messageId: fields[12] as String?, inReplyTo: fields[13] as String?, ); } @override void write(BinaryWriter writer, StorageMessageEnvelope obj) { writer ..writeByte(14) ..writeByte(0) ..write(obj.flags) ..writeByte(1) ..write(obj.uid) ..writeByte(2) ..write(obj.guid) ..writeByte(3) ..write(obj.sequenceId) ..writeByte(4) ..write(obj.sender) ..writeByte(5) ..write(obj.from) ..writeByte(6) ..write(obj.replyTo) ..writeByte(7) ..write(obj.to) ..writeByte(8) ..write(obj.cc) ..writeByte(9) ..write(obj.bcc) ..writeByte(10) ..write(obj.subject) ..writeByte(11) ..write(obj.date) ..writeByte(12) ..write(obj.messageId) ..writeByte(13) ..write(obj.inReplyTo); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is StorageMessageEnvelopeAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/extensions/extension_action_tile.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:url_launcher/url_launcher.dart' hide WebViewConfiguration; import '../account/model.dart'; import '../localization/extension.dart'; import '../models/models.dart'; import '../routes/routes.dart'; import 'extensions.dart'; class ExtensionActionTile extends ConsumerWidget { const ExtensionActionTile({super.key, required this.actionDescription}); final AppExtensionActionDescription actionDescription; static Widget buildSideMenuForAccount( BuildContext context, RealAccount? currentAccount, ) { if (currentAccount == null || currentAccount.isVirtual) { return Container(); } final actions = currentAccount.appExtensionsAccountSideMenu; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: buildActionWidgets(context, actions), ); } static List<Widget> buildActionWidgets( BuildContext context, List<AppExtensionActionDescription> actions, { bool withDivider = true, }) { if (actions.isEmpty) { return []; } final widgets = <Widget>[]; if (withDivider) { widgets.add(const Divider()); } for (final action in actions) { widgets.add(ExtensionActionTile(actionDescription: action)); } return widgets; } @override Widget build(BuildContext context, WidgetRef ref) { final languageCode = ref.text.localeName; final icon = actionDescription.icon; return PlatformListTile( leading: icon == null ? null : Image.network( icon, height: 24, width: 24, ), title: Text(actionDescription.getLabel(languageCode) ?? ''), onTap: () { final action = actionDescription.action; if (action == null) { return; } final url = action.url; switch (action.mechanism) { case AppExtensionActionMechanism.inApp: final context = Routes.navigatorKey.currentContext; if (context != null) { if (!useAppDrawerAsRoot) { // close app drawer: context.pop(); } context.pushNamed( Routes.webview, extra: WebViewConfiguration( actionDescription.getLabel(languageCode), Uri.parse(url), ), ); } break; case AppExtensionActionMechanism.external: launchUrl(Uri.parse(url)); break; } }, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/extensions/extensions.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'extensions.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** AppExtension _$AppExtensionFromJson(Map<String, dynamic> json) => AppExtension( version: json['version'] as int?, accountSideMenu: (json['accountSideMenu'] as List<dynamic>?) ?.map((e) => AppExtensionActionDescription.fromJson(e as Map<String, dynamic>)) .toList(), forgotPasswordAction: json['forgotPassword'] == null ? null : AppExtensionActionDescription.fromJson( json['forgotPassword'] as Map<String, dynamic>), signatureHtml: (json['signatureHtml'] as Map<String, dynamic>?)?.map( (k, e) => MapEntry(k, e as String), ), ); Map<String, dynamic> _$AppExtensionToJson(AppExtension instance) => <String, dynamic>{ 'version': instance.version, 'accountSideMenu': instance.accountSideMenu, 'forgotPassword': instance.forgotPasswordAction, 'signatureHtml': instance.signatureHtml, }; AppExtensionActionDescription _$AppExtensionActionDescriptionFromJson( Map<String, dynamic> json) => AppExtensionActionDescription( action: AppExtensionAction._parse(json['action'] as String?), icon: json['icon'] as String?, labelByLanguage: (json['label'] as Map<String, dynamic>?)?.map( (k, e) => MapEntry(k, e as String), ), ); Map<String, dynamic> _$AppExtensionActionDescriptionToJson( AppExtensionActionDescription instance) => <String, dynamic>{ 'action': AppExtensionAction._toJson(instance.action), 'icon': instance.icon, 'label': instance.labelByLanguage, }; AppExtensionAction _$AppExtensionActionFromJson(Map<String, dynamic> json) => AppExtensionAction( mechanism: $enumDecode(_$AppExtensionActionMechanismEnumMap, json['mechanism']), url: json['url'] as String, ); Map<String, dynamic> _$AppExtensionActionToJson(AppExtensionAction instance) => <String, dynamic>{ 'mechanism': _$AppExtensionActionMechanismEnumMap[instance.mechanism]!, 'url': instance.url, }; const _$AppExtensionActionMechanismEnumMap = { AppExtensionActionMechanism.inApp: 'inApp', AppExtensionActionMechanism.external: 'external', };
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/extensions/extensions.dart
import 'dart:convert'; import 'package:collection/collection.dart' show IterableExtension; import 'package:enough_mail/enough_mail.dart'; import 'package:http/http.dart' as http; import 'package:json_annotation/json_annotation.dart'; import '../account/model.dart'; import '../logger.dart'; import '../util/http_helper.dart'; part 'extensions.g.dart'; /// Server side mail account extensions extension MailAccountExtension on RealAccount { /// The forgot password app extension for this account AppExtensionActionDescription? get appExtensionForgotPassword => appExtensions ?.firstWhereOrNull((ext) => ext.forgotPasswordAction != null) ?.forgotPasswordAction; /// The menu app extensions for this account List<AppExtensionActionDescription> get appExtensionsAccountSideMenu { final entries = <AppExtensionActionDescription>[]; final extensions = appExtensions; if (extensions != null) { for (final ext in extensions) { final accountSideMenu = ext.accountSideMenu; if (accountSideMenu != null) { entries.addAll(accountSideMenu); } } } return entries; } } /// [AppExtension]s allow to dynamically configure the app for a /// given [MailAccount] @JsonSerializable() class AppExtension { /// Creates a new [AppExtension] const AppExtension({ this.version, this.accountSideMenu, this.forgotPasswordAction, this.signatureHtml, }); /// Creates a new [AppExtension] from the given [json] factory AppExtension.fromJson(Map<String, dynamic> json) => _$AppExtensionFromJson(json); /// The version of the app extension final int? version; /// Elements to add to the account side/hamburger menu final List<AppExtensionActionDescription>? accountSideMenu; /// The action to perform when the user forgot the password @JsonKey(name: 'forgotPassword') final AppExtensionActionDescription? forgotPasswordAction; /// The signature html for each language final Map<String, String>? signatureHtml; /// The signature html for the given [languageCode]. /// /// Falls back to `en` if no signature for the given [languageCode] is found. String? getSignatureHtml(String languageCode) { final map = signatureHtml; if (map == null) { return null; } var signature = map[languageCode]; if (signature == null && languageCode != 'en') { signature = map['en']; } return signature; } /// Converts this [AppExtension] to JSON. Map<String, dynamic> toJson() => _$AppExtensionToJson(this); /// REtrieves the app extension url for the given [domain] static String urlFor(String domain) => 'https://$domain/.maily.json'; //// Loads the app extensions for the given [mailAccount] static Future<List<AppExtension>> loadFor(MailAccount mailAccount) async { try { final domains = <String, Future<AppExtension?>>{}; _addEmail(mailAccount.email, domains); final incomingHostname = mailAccount.incoming.serverConfig.hostname; _addHostname(incomingHostname, domains); final outgoingHostname = mailAccount.outgoing.serverConfig.hostname; _addHostname(outgoingHostname, domains); final allExtensions = await Future.wait(domains.values); final appExtensions = <AppExtension>[]; for (final ext in allExtensions) { if (ext != null) { appExtensions.add(ext); } } return appExtensions; } catch (e, s) { logger.e( 'Unable to load app extensions for mail account ' '${mailAccount.email}: $e', error: e, stackTrace: s, ); return const []; } } static void _addEmail( String email, Map<String, Future<AppExtension?>> domains, ) { _addDomain(email.substring(email.indexOf('@') + 1), domains); } static void _addHostname( String hostname, Map<String, Future<AppExtension?>> domains, ) { final domainIndex = hostname.indexOf('.'); if (domainIndex != -1) { _addDomain(hostname.substring(domainIndex + 1), domains); } } static void _addDomain( String domain, Map<String, Future<AppExtension?>> domains, ) { if (!domains.containsKey(domain)) { domains[domain] = loadFrom(domain); } } /// Loads the app extension from the given [domain] static Future<AppExtension?> loadFrom(String domain) async => loadFromUrl(urlFor(domain)); /// Loads the app extension from the given [url] static Future<AppExtension?> loadFromUrl( String url, { Duration timeout = const Duration(seconds: 10), }) async { String? text = '<>'; try { final response = await http.get(Uri.parse(url)).timeout(timeout); if (response.statusCode != 200) { return null; } text = response.text; if (text == null || text.isEmpty) { return null; } final result = AppExtension.fromJson(jsonDecode(text)); if (result.version == 1) { return result; } } catch (e, s) { logger.e( 'Unable to load extension from $url / text $text: $e', error: e, stackTrace: s, ); return null; } return null; } } /// Defines a translatable action @JsonSerializable() class AppExtensionActionDescription { /// Creates a new [AppExtensionActionDescription] const AppExtensionActionDescription({ this.action, this.icon, this.labelByLanguage, }); /// Creates a new [AppExtensionActionDescription] from the given [json] factory AppExtensionActionDescription.fromJson(Map<String, dynamic> json) => _$AppExtensionActionDescriptionFromJson(json); /// The action to perform @JsonKey( fromJson: AppExtensionAction._parse, toJson: AppExtensionAction._toJson, ) final AppExtensionAction? action; /// The icon to display final String? icon; /// The label to display for each language @JsonKey(name: 'label') final Map<String, String>? labelByLanguage; /// The label to display for the given [languageCode] /// /// Falls back to `en` if no label for the given [languageCode] is found. String? getLabel(String languageCode) { final map = labelByLanguage; if (map == null) { return null; } return map[languageCode] ?? map['en']; } /// Converts this [AppExtensionActionDescription] to JSON. Map<String, dynamic> toJson() => _$AppExtensionActionDescriptionToJson(this); } /// Defines an action enum AppExtensionActionMechanism { /// An action is opened in-app inApp, /// An action is opened in an external app/browser external, } /// Defines an action @JsonSerializable() class AppExtensionAction { /// Creates a new [AppExtensionAction] const AppExtensionAction({ required this.mechanism, required this.url, }); /// Creates a new [AppExtensionAction] from the given [json] factory AppExtensionAction.fromJson(Map<String, dynamic> json) => _$AppExtensionActionFromJson(json); /// The action mechanism final AppExtensionActionMechanism mechanism; /// The url to open final String url; /// Converts this [AppExtensionAction] to JSON. Map<String, dynamic> toJson() => _$AppExtensionActionToJson(this); static AppExtensionAction? _parse(String? link) { if (link == null || link.isEmpty) { return null; } final splitIndex = link.indexOf(':'); if (splitIndex == -1 || splitIndex == link.length - 1) { return null; } final mechanismText = link.substring(0, splitIndex); final mechanism = (mechanismText.toLowerCase() == 'inapp') ? AppExtensionActionMechanism.inApp : AppExtensionActionMechanism.external; final url = link.substring(splitIndex + 1); return AppExtensionAction(mechanism: mechanism, url: url); } static String? _toJson(AppExtensionAction? action) { if (action == null) { return null; } return '${action.mechanism.toString()}:${action.url}'; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/account/account.dart
export 'model.dart'; export 'provider.dart'; export 'storage.dart';
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/account/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$sendersHash() => r'7d45f5bd244bb17ed18983d9eac9a6170dfde855'; /// Generates a list of senders for composing a new message /// /// Copied from [senders]. @ProviderFor(senders) final sendersProvider = AutoDisposeProvider<List<Sender>>.internal( senders, name: r'sendersProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$sendersHash, dependencies: null, allTransitiveDependencies: null, ); typedef SendersRef = AutoDisposeProviderRef<List<Sender>>; String _$unifiedAccountHash() => r'5380f681599f9354b8ecd0cbda4c40dedd9de535'; /// Provides the unified account, if any /// /// Copied from [unifiedAccount]. @ProviderFor(unifiedAccount) final unifiedAccountProvider = Provider<UnifiedAccount?>.internal( unifiedAccount, name: r'unifiedAccountProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$unifiedAccountHash, dependencies: null, allTransitiveDependencies: null, ); typedef UnifiedAccountRef = ProviderRef<UnifiedAccount?>; String _$findAccountByEmailHash() => r'692760656b2f9223f3ef929e040c413f2dd4c571'; /// Copied from Dart SDK class _SystemHash { _SystemHash._(); static int combine(int hash, int value) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + value); // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int finish(int hash) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); // ignore: parameter_assignments hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } } //// Finds an account by its email /// /// Copied from [findAccountByEmail]. @ProviderFor(findAccountByEmail) const findAccountByEmailProvider = FindAccountByEmailFamily(); //// Finds an account by its email /// /// Copied from [findAccountByEmail]. class FindAccountByEmailFamily extends Family<Account?> { //// Finds an account by its email /// /// Copied from [findAccountByEmail]. const FindAccountByEmailFamily(); //// Finds an account by its email /// /// Copied from [findAccountByEmail]. FindAccountByEmailProvider call({ required String email, }) { return FindAccountByEmailProvider( email: email, ); } @override FindAccountByEmailProvider getProviderOverride( covariant FindAccountByEmailProvider provider, ) { return call( email: provider.email, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'findAccountByEmailProvider'; } //// Finds an account by its email /// /// Copied from [findAccountByEmail]. class FindAccountByEmailProvider extends Provider<Account?> { //// Finds an account by its email /// /// Copied from [findAccountByEmail]. FindAccountByEmailProvider({ required String email, }) : this._internal( (ref) => findAccountByEmail( ref as FindAccountByEmailRef, email: email, ), from: findAccountByEmailProvider, name: r'findAccountByEmailProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$findAccountByEmailHash, dependencies: FindAccountByEmailFamily._dependencies, allTransitiveDependencies: FindAccountByEmailFamily._allTransitiveDependencies, email: email, ); FindAccountByEmailProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.email, }) : super.internal(); final String email; @override Override overrideWith( Account? Function(FindAccountByEmailRef provider) create, ) { return ProviderOverride( origin: this, override: FindAccountByEmailProvider._internal( (ref) => create(ref as FindAccountByEmailRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, email: email, ), ); } @override ProviderElement<Account?> createElement() { return _FindAccountByEmailProviderElement(this); } @override bool operator ==(Object other) { return other is FindAccountByEmailProvider && other.email == email; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, email.hashCode); return _SystemHash.finish(hash); } } mixin FindAccountByEmailRef on ProviderRef<Account?> { /// The parameter `email` of this provider. String get email; } class _FindAccountByEmailProviderElement extends ProviderElement<Account?> with FindAccountByEmailRef { _FindAccountByEmailProviderElement(super.provider); @override String get email => (origin as FindAccountByEmailProvider).email; } String _$findRealAccountByEmailHash() => r'4fbe9680f101417c67bc9eebda553005f78d77c1'; //// Finds a real account by its email /// /// Copied from [findRealAccountByEmail]. @ProviderFor(findRealAccountByEmail) const findRealAccountByEmailProvider = FindRealAccountByEmailFamily(); //// Finds a real account by its email /// /// Copied from [findRealAccountByEmail]. class FindRealAccountByEmailFamily extends Family<RealAccount?> { //// Finds a real account by its email /// /// Copied from [findRealAccountByEmail]. const FindRealAccountByEmailFamily(); //// Finds a real account by its email /// /// Copied from [findRealAccountByEmail]. FindRealAccountByEmailProvider call({ required String email, }) { return FindRealAccountByEmailProvider( email: email, ); } @override FindRealAccountByEmailProvider getProviderOverride( covariant FindRealAccountByEmailProvider provider, ) { return call( email: provider.email, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'findRealAccountByEmailProvider'; } //// Finds a real account by its email /// /// Copied from [findRealAccountByEmail]. class FindRealAccountByEmailProvider extends Provider<RealAccount?> { //// Finds a real account by its email /// /// Copied from [findRealAccountByEmail]. FindRealAccountByEmailProvider({ required String email, }) : this._internal( (ref) => findRealAccountByEmail( ref as FindRealAccountByEmailRef, email: email, ), from: findRealAccountByEmailProvider, name: r'findRealAccountByEmailProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$findRealAccountByEmailHash, dependencies: FindRealAccountByEmailFamily._dependencies, allTransitiveDependencies: FindRealAccountByEmailFamily._allTransitiveDependencies, email: email, ); FindRealAccountByEmailProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.email, }) : super.internal(); final String email; @override Override overrideWith( RealAccount? Function(FindRealAccountByEmailRef provider) create, ) { return ProviderOverride( origin: this, override: FindRealAccountByEmailProvider._internal( (ref) => create(ref as FindRealAccountByEmailRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, email: email, ), ); } @override ProviderElement<RealAccount?> createElement() { return _FindRealAccountByEmailProviderElement(this); } @override bool operator ==(Object other) { return other is FindRealAccountByEmailProvider && other.email == email; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, email.hashCode); return _SystemHash.finish(hash); } } mixin FindRealAccountByEmailRef on ProviderRef<RealAccount?> { /// The parameter `email` of this provider. String get email; } class _FindRealAccountByEmailProviderElement extends ProviderElement<RealAccount?> with FindRealAccountByEmailRef { _FindRealAccountByEmailProviderElement(super.provider); @override String get email => (origin as FindRealAccountByEmailProvider).email; } String _$hasAccountWithErrorHash() => r'df9f05a11751823686a4b6dc985e5cae0224a07f'; //// Checks if there is at least one real account with a login error /// /// Copied from [hasAccountWithError]. @ProviderFor(hasAccountWithError) final hasAccountWithErrorProvider = Provider<bool>.internal( hasAccountWithError, name: r'hasAccountWithErrorProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$hasAccountWithErrorHash, dependencies: null, allTransitiveDependencies: null, ); typedef HasAccountWithErrorRef = ProviderRef<bool>; String _$currentRealAccountHash() => r'dd79b65ff2ea824e117c4f13416c6b6993fa4a86'; /// Provides the current real account /// /// Copied from [currentRealAccount]. @ProviderFor(currentRealAccount) final currentRealAccountProvider = AutoDisposeProvider<RealAccount?>.internal( currentRealAccount, name: r'currentRealAccountProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$currentRealAccountHash, dependencies: null, allTransitiveDependencies: null, ); typedef CurrentRealAccountRef = AutoDisposeProviderRef<RealAccount?>; String _$realAccountsHash() => r'cf98cca42c7239746aea0af704cbf02a96108a7f'; /// Provides all real email accounts /// /// Copied from [RealAccounts]. @ProviderFor(RealAccounts) final realAccountsProvider = NotifierProvider<RealAccounts, List<RealAccount>>.internal( RealAccounts.new, name: r'realAccountsProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$realAccountsHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$RealAccounts = Notifier<List<RealAccount>>; String _$allAccountsHash() => r'72f9626b7f40dfa85b19cbc7a694494a13b9638f'; /// Provides all accounts /// /// Copied from [AllAccounts]. @ProviderFor(AllAccounts) final allAccountsProvider = NotifierProvider<AllAccounts, List<Account>>.internal( AllAccounts.new, name: r'allAccountsProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$allAccountsHash, dependencies: null, allTransitiveDependencies: null, ); typedef _$AllAccounts = Notifier<List<Account>>; // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/account/storage.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'model.dart'; /// Allows to load and store accounts class AccountStorage { /// Creates a new [AccountStorage] const AccountStorage(); static const String _keyAccounts = 'accts'; static const String _keyFirstRun = 'firstRun'; FlutterSecureStorage get _storage => const FlutterSecureStorage(); /// Loads the accounts from the storage Future<List<RealAccount>> loadAccounts() async { // on iOS the key chain keeps all data even after the app is uninstalled // so we need to delete all data if the app is started for the first time if (defaultTargetPlatform == TargetPlatform.iOS) { final preferences = await SharedPreferences.getInstance(); if (preferences.getBool(_keyFirstRun) ?? true) { const FlutterSecureStorage storage = FlutterSecureStorage(); await storage.deleteAll(); await preferences.setBool(_keyFirstRun, false); } } final jsonText = await _storage.read(key: _keyAccounts); if (jsonText == null) { return <RealAccount>[]; } final accountsJson = jsonDecode(jsonText) as List; try { // ignore: unnecessary_lambdas return accountsJson.map((json) => RealAccount.fromJson(json)).toList(); } catch (e) { if (kDebugMode) { print('Unable to parse accounts: $e'); print(jsonText); } return <RealAccount>[]; } } /// Saves the given [accounts] to the storage Future<void> saveAccounts(List<Account> accounts) { final accountsJson = accounts.whereType<RealAccount>().map((a) => a.toJson()).toList(); final json = jsonEncode(accountsJson); return _storage.write(key: _keyAccounts, value: json); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/account/model.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'model.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** RealAccount _$RealAccountFromJson(Map<String, dynamic> json) => RealAccount( MailAccount.fromJson(json['mailAccount'] as Map<String, dynamic>), appExtensions: (json['appExtensions'] as List<dynamic>?) ?.map((e) => AppExtension.fromJson(e as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> _$RealAccountToJson(RealAccount instance) => <String, dynamic>{ 'mailAccount': instance.mailAccount, 'appExtensions': instance.appExtensions, };
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/account/provider.dart
import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../logger.dart'; import '../models/sender.dart'; import 'model.dart'; import 'storage.dart'; part 'provider.g.dart'; /// Provides all real email accounts @Riverpod(keepAlive: true) class RealAccounts extends _$RealAccounts { late AccountStorage _storage; @override List<RealAccount> build() => []; /// Loads the accounts from disk Future<void> init() async { _storage = const AccountStorage(); final accounts = await _storage.loadAccounts(); if (accounts.isNotEmpty) { ref.read(currentAccountProvider.notifier).state = accounts.first; } state = accounts; } /// Adds a new account void addAccount(RealAccount account) { final cleanState = state.toList()..removeWhere((a) => a.key == account.key); state = [...cleanState, account]; if (state.length == 1) { ref.read(currentAccountProvider.notifier).state = account; } _saveAccounts(); } /// Removes the given [account] void removeAccount(RealAccount account) { state = state.where((a) => a.key != account.key).toList(); if (ref.read(currentAccountProvider) == account) { final replacement = state.isEmpty ? null : state.first; ref.read(currentAccountProvider.notifier).state = replacement; } _saveAccounts(); } /// Updates the given [oldAccount] with the given [newAccount] void replaceAccount({ required RealAccount oldAccount, required RealAccount newAccount, bool save = true, }) { final index = state.indexWhere((a) => a.key == oldAccount.key); if (index == -1) { throw StateError('account not found for ${oldAccount.key}'); } final newState = state.toList()..[index] = newAccount; state = newState; if (ref.read(currentAccountProvider) == oldAccount) { ref.read(currentAccountProvider.notifier).state = newAccount; } if (save) { _saveAccounts(); } } /// Changes the order of the accounts void reorderAccounts(List<RealAccount> accounts) { state = accounts; _saveAccounts(); } /// Saves all data Future<void> updateMailAccount(RealAccount account, MailAccount mailAccount) { account.mailAccount = mailAccount; return _saveAccounts(); } /// Saves all data Future<void> save() => _saveAccounts(); Future<void> _saveAccounts() async { await _storage.saveAccounts(state); } } /// Generates a list of senders for composing a new message @riverpod List<Sender> senders(SendersRef ref) { final accounts = ref.watch(realAccountsProvider); final senders = <Sender>[]; for (final account in accounts) { senders.add(Sender(account.fromAddress, account)); for (final alias in account.aliases) { senders.add(Sender(alias, account)); } } return senders; } /// Provides the unified account, if any @Riverpod(keepAlive: true) UnifiedAccount? unifiedAccount(UnifiedAccountRef ref) { final allRealAccounts = ref.watch(realAccountsProvider); final accounts = allRealAccounts.where((a) => !a.excludeFromUnified).toList(); if (accounts.length <= 1) { return null; } final account = UnifiedAccount(accounts); final currentAccount = ref.read(currentAccountProvider); Future.delayed(const Duration(milliseconds: 20)).then((_) { if (currentAccount == null || currentAccount is RealAccount) { ref.read(currentAccountProvider.notifier).state = account; } }); return account; } /// Provides all accounts @Riverpod(keepAlive: true) class AllAccounts extends _$AllAccounts { @override List<Account> build() { final realAccounts = ref.watch(realAccountsProvider); final unifiedAccount = ref.watch(unifiedAccountProvider); logger.d('Creating all accounts'); return [ if (unifiedAccount != null) unifiedAccount, ...realAccounts, ]; } } //// Finds an account by its email @Riverpod(keepAlive: true) Account? findAccountByEmail( FindAccountByEmailRef ref, { required String email, }) { final key = email.toLowerCase(); final realAccounts = ref.watch(realAccountsProvider); final unifiedAccount = ref.watch(unifiedAccountProvider); return realAccounts.firstWhereOrNull((a) => a.key == key) ?? ((unifiedAccount?.key == key) ? unifiedAccount : null); } //// Finds a real account by its email @Riverpod(keepAlive: true) RealAccount? findRealAccountByEmail( FindRealAccountByEmailRef ref, { required String email, }) { final key = email.toLowerCase(); final realAccounts = ref.watch(realAccountsProvider); return realAccounts.firstWhereOrNull((a) => a.key == key); } //// Checks if there is at least one real account with a login error @Riverpod(keepAlive: true) bool hasAccountWithError( HasAccountWithErrorRef ref, ) { final realAccounts = ref.watch(realAccountsProvider); return realAccounts.any((a) => a.hasError); } /// Provides the locally current active account final currentAccountProvider = StateProvider<Account?>((ref) => null); /// Provides the current real account @riverpod RealAccount? currentRealAccount(CurrentRealAccountRef ref) { final realAccounts = ref.watch(realAccountsProvider); final providedCurrentAccount = ref.watch(currentAccountProvider); return providedCurrentAccount is RealAccount ? providedCurrentAccount : (providedCurrentAccount is UnifiedAccount ? providedCurrentAccount.accounts.first : (realAccounts.isNotEmpty ? realAccounts.first : null)); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/account/model.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/cupertino.dart'; import 'package:json_annotation/json_annotation.dart'; import '../contact/model.dart'; import '../extensions/extensions.dart'; part 'model.g.dart'; /// Common functionality for accounts abstract class Account extends ChangeNotifier { /// Is this a virtual account, e.g. a unified one? bool get isVirtual; /// The name of the account String get name; set name(String value); /// Retrieves the email or emails associated with this account String get email; /// The from address for this account MailAddress get fromAddress; /// The key for comparing accounts String get key { final value = _key ?? email.toLowerCase(); _key = value; return value; } String? _key; @override int get hashCode => key.hashCode; @override bool operator ==(Object other) => other is Account && other.key == key; } /// Allows to listen to mail account changes @JsonSerializable() class RealAccount extends Account { /// Creates a new [Account] RealAccount( MailAccount mailAccount, { this.appExtensions, this.contactManager, }) : _account = mailAccount; /// Creates a new [RealAccount] from JSON factory RealAccount.fromJson(Map<String, dynamic> json) => _$RealAccountFromJson(json); /// Generates JSON from this [MailAccount] Map<String, dynamic> toJson() => _$RealAccountToJson(this); static const String attributeGravatarImageUrl = 'gravatar.img'; static const String attributeExcludeFromUnified = 'excludeUnified'; static const String attributePlusAliasTested = 'test.alias.plus'; static const String attributeSentMailAddedAutomatically = 'sendMailAdded'; static const String attributeSignatureHtml = 'signatureHtml'; static const String attributeSignaturePlain = 'signaturePlain'; static const String attributeBccMyself = 'bccMyself'; static const String attributeEnableLogging = 'enableLogging'; /// The underlying actual account @JsonKey(name: 'mailAccount', required: true) MailAccount _account; /// Retrieves the mail account MailAccount get mailAccount => _account; /// Updates the account with the given [mailAccount] set mailAccount(MailAccount mailAccount) { _account = mailAccount; notifyListeners(); } /// Does this account have a login error? @JsonKey(includeToJson: false, includeFromJson: false) bool hasError = false; @override bool get isVirtual => false; @JsonKey(includeToJson: false, includeFromJson: false) @override String get name => _account.name; @override set name(String value) { _account = _account.copyWith(name: value); notifyListeners(); } /// Should this account be excluded from the unified account? @JsonKey(includeToJson: false, includeFromJson: false) bool get excludeFromUnified => getAttribute(attributeExcludeFromUnified) ?? false; set excludeFromUnified(bool value) => setAttribute(attributeExcludeFromUnified, value); /// Developer mode option: should logging be enabled for this account? @JsonKey(includeToJson: false, includeFromJson: false) bool get enableLogging => getAttribute(attributeEnableLogging) ?? false; set enableLogging(bool value) => setAttribute(attributeEnableLogging, value); /// Retrieves the attribute with the given [key] name T? getAttribute<T>(String key) => _account.attributes[key] as T?; /// Sets the attribute [key] to [value] void setAttribute(String key, dynamic value) { if (value == null) { _account.attributes.remove(key); } else { _account = _account.copyWithAttribute(key, value); } notifyListeners(); } /// Checks is this account has the [key] attribute bool hasAttribute(String key) => _account.hasAttribute(key); /// Retrieves the account specific signature for HTML messages /// Compare [signaturePlain] String? getSignatureHtml([String? languageCode]) { final signature = _account.attributes[attributeSignatureHtml]; if (signature == null) { final extensions = appExtensions; if (extensions != null) { for (final ext in extensions) { final signature = ext.getSignatureHtml(languageCode ?? 'en'); if (signature != null) { return signature; } } } } return signature; } /// Sets the account specific signature for HTML messages // ignore: avoid_setters_without_getters set signatureHtml(String? value) => setAttribute(attributeSignatureHtml, value); /// Account-specific signature for plain text messages /// /// Compare [signatureHtml] @JsonKey(includeToJson: false, includeFromJson: false) String? get signaturePlain => _account.attributes[attributeSignaturePlain]; set signaturePlain(String? value) => setAttribute(attributeSignaturePlain, value); /// The name used for sending @JsonKey(includeToJson: false, includeFromJson: false) String? get userName => _account.userName; set userName(String? value) { _account = _account.copyWith(userName: value); notifyListeners(); } /// The email associated with this account @override @JsonKey(includeToJson: false, includeFromJson: false) String get email => _account.email; set email(String value) { _account = _account.copyWith(email: value); notifyListeners(); } @override MailAddress get fromAddress => _account.fromAddress; /// Does this account support + aliases like name+alias@domain.com? @JsonKey(includeToJson: false, includeFromJson: false) bool get supportsPlusAliases => _account.supportsPlusAliases; set supportsPlusAliases(bool value) { _account = _account.copyWith(supportsPlusAliases: value); notifyListeners(); } /// Should all outgoing messages be sent to the user as well? @JsonKey(includeToJson: false, includeFromJson: false) bool get bccMyself => _account.hasAttribute(attributeBccMyself); set bccMyself(bool value) { if (value) { setAttribute(attributeBccMyself, value); } else { _account.attributes.remove(attributeBccMyself); } notifyListeners(); } /// Allows to access the [ContactManager] @JsonKey(includeFromJson: false, includeToJson: false) ContactManager? contactManager; /// Adds the [alias] void addAlias(MailAddress alias) { _account = _account.copyWithAlias(alias); notifyListeners(); } /// Removes the [alias] void removeAlias(MailAddress alias) { _account.aliases.remove(alias); notifyListeners(); } /// Retrieves the known alias addresses List<MailAddress> get aliases => _account.aliases; /// Checks if this account has at least 1 alias bool get hasAlias => _account.aliases.isNotEmpty; /// Checks if this account has now alias bool get hasNoAlias => _account.aliases.isEmpty; /// Retrieves the gravatar image URl for this email String? get imageUrlGravatar => _account.attributes[attributeGravatarImageUrl]; /// Marks if this account adds sent messages to the default SENT mailbox /// folder automatically bool get addsSentMailAutomatically => _account.attributes[attributeSentMailAddedAutomatically] ?? false; /// [AppExtension]s are account specific additional setting retrieved /// from the server during initial setup /// Retrieves the app extensions List<AppExtension>? appExtensions; /// Copies this account with the given data RealAccount copyWith({ MailAccount? mailAccount, List<AppExtension>? appExtensions, ContactManager? contactManager, }) => RealAccount( mailAccount ?? _account, appExtensions: appExtensions ?? this.appExtensions, contactManager: contactManager ?? this.contactManager, ); } /// A unified account bundles folders of several accounts class UnifiedAccount extends Account { /// Creates a new [UnifiedAccount] UnifiedAccount(this.accounts); /// The accounts final List<RealAccount> accounts; @override bool get isVirtual => true; @override String get name => ''; @override set name(String value) { //_name = value; notifyListeners(); } @override MailAddress get fromAddress => accounts.first.fromAddress; /// The emails of this account @override String get email => accounts.map((a) => a.email).join(';'); /// Removes the given [account] void removeAccount(RealAccount account) { accounts.remove(account); } /// Adds the given [account] void addAccount(RealAccount account) { accounts.add(account); } } /// A account with an active [MailClient] class ConnectedAccount extends RealAccount { /// Creates a new [ConnectedAccount] ConnectedAccount(super.account, this.mailClient); /// The client final MailClient mailClient; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/date_helper.dart
/// The date section of a given date enum DateSectionRange { /// The date is in the future, more distant than tomorrow future, /// The date is tomorrow tomorrow, /// The date is today today, /// The date is yesterday yesterday, /// The date is in the current week thisWeek, /// The date is in the last week lastWeek, /// The date is in the current month thisMonth, /// The date is in the current year monthOfThisYear, /// The date is in a different year monthAndYear, } /// Allows to determine the date section of a given date class DateHelper { /// Creates a new [DateHelper] DateHelper(this.firstDayOfWeek) { _setupDates(); } /// The first weekday of the week final int firstDayOfWeek; late DateTime _today; late DateTime _tomorrow; late DateTime _dayAfterTomorrow; late DateTime _yesterday; late DateTime _thisWeek; late DateTime _lastWeek; void _setupDates() { final now = DateTime.now(); _today = DateTime(now.year, now.month, now.day); _tomorrow = _today.add(const Duration(days: 1)); _dayAfterTomorrow = _tomorrow.add(const Duration(days: 1)); _yesterday = _today.subtract(const Duration(days: 1)); if (_today.weekday == firstDayOfWeek) { _thisWeek = _today; } else if (_yesterday.weekday == firstDayOfWeek) { _thisWeek = _yesterday; } else { _thisWeek = _today.weekday > firstDayOfWeek ? _today.subtract(Duration(days: _today.weekday - firstDayOfWeek)) : _today .subtract(Duration(days: _today.weekday + 7 - firstDayOfWeek)); } _lastWeek = _thisWeek.subtract(const Duration(days: 7)); } /// Determines the date section of the given [localTime] DateSectionRange determineDateSection( DateTime localTime, ) { if (_today.weekday != DateTime.now().weekday) { _setupDates(); } if (localTime.isAfter(_today)) { return localTime.isBefore(_tomorrow) ? DateSectionRange.today : localTime.isBefore(_dayAfterTomorrow) ? DateSectionRange.tomorrow : DateSectionRange.future; } if (localTime.isAfter(_yesterday)) { return DateSectionRange.yesterday; } else if (localTime.isAfter(_thisWeek)) { return DateSectionRange.thisWeek; } else if (localTime.isAfter(_lastWeek)) { return DateSectionRange.lastWeek; } else if (localTime.year == _today.year) { return localTime.month == _today.month ? DateSectionRange.thisMonth : DateSectionRange.monthOfThisYear; } return DateSectionRange.monthAndYear; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/datetime.dart
import 'package:flutter/material.dart'; extension DateTimeExtension on DateTime { TimeOfDay toTimeOfDay() => TimeOfDay.fromDateTime(this); DateTime withTimeOfDay(TimeOfDay timeOfDay) => DateTime(year, month, day, timeOfDay.hour, timeOfDay.minute); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/modal_bottom_sheet_helper.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:modal_bottom_sheet/modal_bottom_sheet.dart'; import '../screens/base.dart'; /// Helps to show a modal bottom sheet class ModelBottomSheetHelper { ModelBottomSheetHelper._(); /// Shows a modal bottom sheet static Future<T?> showModalBottomSheet<T>( BuildContext context, String title, Widget child, { List<Widget>? appBarActions, bool useScrollView = true, }) async { appBarActions ??= [ DensePlatformIconButton( icon: Icon(CommonPlatformIcons.ok), onPressed: () => context.pop(true), ), ]; final bottomSheetContent = SafeArea( bottom: false, child: Padding( padding: const EdgeInsets.only(top: 32), child: BasePage( title: title, includeDrawer: false, appBarActions: appBarActions, content: useScrollView ? SingleChildScrollView( child: SafeArea( child: child, ), ) : SafeArea(child: child), ), ), ); return PlatformInfo.isCupertino ? await showCupertinoModalBottomSheet<T>( context: context, builder: (context) => bottomSheetContent, elevation: 8, expand: true, isDismissible: true, ) : await showMaterialModalBottomSheet<T>( context: context, builder: (context) => bottomSheetContent, elevation: 8, expand: true, backgroundColor: Colors.transparent, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/validator.dart
class Validator { static bool validateEmail(String value) { if (value.length < 'a@b.cd'.length) { return false; } final atIndex = value.lastIndexOf('@'); final dotIndex = value.lastIndexOf('.'); return atIndex > 0 && dotIndex > atIndex && dotIndex < value.length - 2; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/indexed_cache.dart
import 'package:collection/collection.dart'; /// Temporarily stores values that can be accessed by an integer index. class IndexedCache<T> { /// Creates a new cache IndexedCache({this.maxCacheSize = defaultMaxCacheSize}); /// default maximum cache size is 200 static const int defaultMaxCacheSize = 200; /// The maximum size of the cache final int maxCacheSize; final _entries = <T?>[]; final _indices = <int>[]; /// Retrieves the first non-null entry of this cache if available. /// /// This operation is independent of an index. T? get first => _entries.firstWhereOrNull((element) => element != null); /// Inserts the [value] at the [index] and changes /// the source indices of subsequent entries void insert(int index, T value) { while (_entries.length <= index) { _entries.add(null); } _entries.insert(index, value); _indices.add(index); if (_indices.length > maxCacheSize) { _shrink(); } } void _shrink() { final removeIndex = _indices.removeAt(0); _entries[removeIndex] = null; } /// Deletes the entry at the given [index] T? removeAt(int index) { if (index > _entries.length) { return null; } final removed = _entries.removeAt(index); if (removed != null) { _indices.remove(index); } return removed; } /// Deletes the entry with the [value] bool remove(T value) { final index = _entries.indexOf(value); if (index == -1) { return false; } removeAt(index); return true; } /// Deletes the entry that matches the given [matcher] function. T? removeFirstWhere(bool Function(T element) matcher) { final index = _entries.indexWhere((value) => value != null && matcher(value)); if (index == -1) { return null; } return removeAt(index); } /// Clears all entries from this cache. void clear() { _entries.clear(); _indices.clear(); } /// Retrieves the value for the given [index]. T? operator [](int index) => index < _entries.length ? _entries[index] : null; /// Set the value for the given [index]. void operator []=(int index, T value) { if (_entries.length > index) { final existing = _entries[index]; _entries[index] = value; if (existing != null) { return; } } else { while (_entries.length < index) { _entries.add(null); } _entries.add(value); } _indices.add(index); if (_indices.length > maxCacheSize) { _shrink(); } } /// Retrieves the first matching element or null when no entry matches T? firstWhereOrNull(bool Function(T element) test) => _entries.firstWhereOrNull((value) => value != null && test(value)); /// Retrieves all cached entries List<T> getAllCachedEntries() => List<T>.from(_entries.where((value) => value != null)); /// Triggers the [action] for any elements that fit the [test] void forEachWhere( bool Function(T element) test, void Function(T element) action, ) { _entries .where((value) => value != null && test(value)) .forEach((element) => action(element as T)); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/gravatar.dart
import 'dart:convert'; import 'package:crypto/crypto.dart'; enum GravatarImage { nf, // 404 mp, // mystery person identicon, monsterid, wavatar, retro, robohash, blank, } enum GravatarRating { g, pg, r, x, } class Gravatar { static String imageUrl( String email, { int? size, GravatarImage? defaultImage, bool forceDefault = false, bool fileExtension = false, GravatarRating? rating, }) { var hashDigest = _generateHash(email); final query = <String, String>{}; if (size != null) query['s'] = size.toString(); if (defaultImage != null) query['d'] = _imageString(defaultImage); if (forceDefault) query['f'] = 'y'; if (rating != null) query['r'] = _ratingString(rating); if (fileExtension) hashDigest += '.png'; return Uri.https( 'www.gravatar.com', '/avatar/$hashDigest', query.isEmpty ? null : query, ).toString(); } static String _generateHash(String email) { final preparedEmail = email.trim().toLowerCase(); return md5.convert(utf8.encode(preparedEmail)).toString(); } static String jsonUrl(String email) { final hash = _generateHash(email); return Uri.https('www.gravatar.com', '/$hash.json').toString(); } static String qrUrl(String email) { final hash = _generateHash(email); return Uri.https('www.gravatar.com', '/$hash.qr').toString(); } static String _imageString(GravatarImage value) { switch (value) { case GravatarImage.nf: return '404'; case GravatarImage.mp: return 'mp'; case GravatarImage.identicon: return 'identicon'; // cSpell: ignore monsterid, wavatar, robohash case GravatarImage.monsterid: return 'monsterid'; case GravatarImage.wavatar: return 'wavatar'; case GravatarImage.retro: return 'retro'; case GravatarImage.robohash: return 'robohash'; case GravatarImage.blank: return 'blank'; } } static String _ratingString(GravatarRating value) { switch (value) { case GravatarRating.g: return 'g'; case GravatarRating.pg: return 'pg'; case GravatarRating.r: return 'r'; case GravatarRating.x: return 'x'; } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/localized_dialog_helper.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:url_launcher/url_launcher.dart' as launcher; import '../localization/extension.dart'; import '../widgets/legalese.dart'; /// Helps to display localized dialogs class LocalizedDialogHelper { LocalizedDialogHelper._(); /// Shows the about dialog static Future<void> showAbout(WidgetRef ref) async { final localizations = ref.text; final packageInfo = await PackageInfo.fromPlatform(); final version = 'v${packageInfo.version}+${packageInfo.buildNumber}'; final context = ref.context; if (context.mounted) { showAboutDialog( context: context, applicationName: 'Maily', applicationVersion: version, applicationIcon: Icon(CommonPlatformIcons.mailRead), applicationLegalese: localizations.aboutApplicationLegalese, children: [ TextButton( child: Text(localizations.feedbackActionSuggestFeature), onPressed: () async { await launcher .launchUrl(Uri.parse('https://maily.userecho.com/')); }, ), TextButton( child: Text(localizations.feedbackActionReportProblem), onPressed: () async { await launcher .launchUrl(Uri.parse('https://maily.userecho.com/')); }, ), TextButton( child: Text(localizations.feedbackActionHelpDeveloping), onPressed: () async { await launcher.launchUrl(Uri.parse( 'https://github.com/Enough-Software/enough_mail_app', )); }, ), const Legalese(), ], ); } } /// Asks the user for confirmation with the given [title] and [query]. /// /// Specify the [action] in case it's different from the title. /// Set [isDangerousAction] to `true` for marking the action as /// dangerous on Cupertino static Future<bool?> askForConfirmation( WidgetRef ref, { required String title, required String query, String? action, bool isDangerousAction = false, }) { final localizations = ref.text; return DialogHelper.askForConfirmation( ref.context, title: title, query: query, action: action, isDangerousAction: isDangerousAction, cancelActionText: localizations.actionCancel, ); } /// Shows a simple text dialog with the given [title] and [text]. /// /// Compare [showWidgetDialog] for parameter details. static Future<T?> showTextDialog<T>( WidgetRef ref, String title, String text, { List<Widget>? actions, }) { final localizations = ref.text; return DialogHelper.showTextDialog<T>( ref.context, title, text, actions: actions, okActionText: localizations.actionOk, cancelActionText: localizations.actionCancel, ); } /// Shows a dialog with the given [content]. /// /// Set the [title] to display the title on top /// /// Specify custom [actions] to provide dialog specific actions, alternatively /// /// specify the [defaultActions]. Without [actions] or [defaultActions] only /// and OK button is shown. /// /// When default actions are used, this method will return `true` when the /// user pressed `ok` and `false` after selecting `cancel`. static Future<T?> showWidgetDialog<T>( WidgetRef ref, Widget content, { String? title, List<Widget>? actions, DialogActions defaultActions = DialogActions.ok, }) { final localizations = ref.text; return DialogHelper.showWidgetDialog<T>( ref.context, content, title: title, actions: actions, defaultActions: defaultActions, okActionText: localizations.actionOk, cancelActionText: localizations.actionCancel, ); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/http_helper.dart
import 'dart:convert'; import 'package:http/http.dart'; /// Extension methods for [Response] extension HttpResponseExtension on Response { /// Retrieves the UTF8 decoded text String? get text => utf8.decode(bodyBytes); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/util/string_helper.dart
import 'dart:math'; /// Helper methods for strings. class StringHelper { StringHelper._(); /// Returns the largest common sequence of the given texts. static String? largestCommonSequence(List<String> texts) { if (texts.isEmpty) { return null; } String? text = texts.first; if (texts.length == 1) { return text; } for (var i = 1; i < texts.length; i++) { text = largestCommonSequenceOf(text ?? '', texts[i]); if (text == null) { return null; } } return text; } /// Returns the largest common sequence of the given texts. static String? largestCommonSequenceOf(String first, String second) { // print('lcs of "$first" and "$second"'); // problem: the longest sequence between first and second is not //necessarily the longest sequence between all String shorter; String longer; if (first.length <= second.length) { shorter = first; longer = second; } else { shorter = second; longer = first; } if (longer.contains(shorter)) { return shorter; } final shorterRunes = shorter.runes.toList(); final longerRunes = longer.runes.toList(); final matches = <_StringSequence>[]; var longestLengthSoFar = 0; for (var sri = 0; sri < shorterRunes.length; sri++) { final shortRune = shorterRunes[sri]; for (var lri = 0; lri < longerRunes.length; lri++) { final longRune = longerRunes[lri]; if (shortRune == longRune) { final maxIndex = min(shorterRunes.length - sri, longerRunes.length - lri); var length = 1; if (length + maxIndex > longestLengthSoFar) { // print('sri: $sri lri: $lri, min: $maxIndex'); for (var i = 1; i < maxIndex; i++) { if (longerRunes[lri + i] != shorterRunes[sri + i]) { break; } length++; } if (length > longestLengthSoFar) { longestLengthSoFar = length; // print('add from $sri with length $length'); matches.add(_StringSequence(sri, length)); } } } } } if (matches.isEmpty) { return null; } var longest = matches.first; for (var i = 1; i < matches.length; i++) { final sequence = matches[i]; if (sequence.length > longest.length) { longest = sequence; } } return String.fromCharCodes( shorterRunes, longest.startIndex, longest.startIndex + longest.length, ); } } class _StringSequence { _StringSequence(this.startIndex, this.length); final int startIndex; final int length; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/contact/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$contactsLoaderHash() => r'2205f8a929faafca4bbffe075c2e3f2961194cbb'; /// Copied from Dart SDK class _SystemHash { _SystemHash._(); static int combine(int hash, int value) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + value); // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int finish(int hash) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); // ignore: parameter_assignments hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } } /// Loads the contacts for the given [account] /// /// Copied from [contactsLoader]. @ProviderFor(contactsLoader) const contactsLoaderProvider = ContactsLoaderFamily(); /// Loads the contacts for the given [account] /// /// Copied from [contactsLoader]. class ContactsLoaderFamily extends Family<AsyncValue<ContactManager>> { /// Loads the contacts for the given [account] /// /// Copied from [contactsLoader]. const ContactsLoaderFamily(); /// Loads the contacts for the given [account] /// /// Copied from [contactsLoader]. ContactsLoaderProvider call({ required RealAccount account, }) { return ContactsLoaderProvider( account: account, ); } @override ContactsLoaderProvider getProviderOverride( covariant ContactsLoaderProvider provider, ) { return call( account: provider.account, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'contactsLoaderProvider'; } /// Loads the contacts for the given [account] /// /// Copied from [contactsLoader]. class ContactsLoaderProvider extends FutureProvider<ContactManager> { /// Loads the contacts for the given [account] /// /// Copied from [contactsLoader]. ContactsLoaderProvider({ required RealAccount account, }) : this._internal( (ref) => contactsLoader( ref as ContactsLoaderRef, account: account, ), from: contactsLoaderProvider, name: r'contactsLoaderProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$contactsLoaderHash, dependencies: ContactsLoaderFamily._dependencies, allTransitiveDependencies: ContactsLoaderFamily._allTransitiveDependencies, account: account, ); ContactsLoaderProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, }) : super.internal(); final RealAccount account; @override Override overrideWith( FutureOr<ContactManager> Function(ContactsLoaderRef provider) create, ) { return ProviderOverride( origin: this, override: ContactsLoaderProvider._internal( (ref) => create(ref as ContactsLoaderRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, ), ); } @override FutureProviderElement<ContactManager> createElement() { return _ContactsLoaderProviderElement(this); } @override bool operator ==(Object other) { return other is ContactsLoaderProvider && other.account == account; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); return _SystemHash.finish(hash); } } mixin ContactsLoaderRef on FutureProviderRef<ContactManager> { /// The parameter `account` of this provider. RealAccount get account; } class _ContactsLoaderProviderElement extends FutureProviderElement<ContactManager> with ContactsLoaderRef { _ContactsLoaderProviderElement(super.provider); @override RealAccount get account => (origin as ContactsLoaderProvider).account; } // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/contact/provider.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../account/model.dart'; import '../account/provider.dart'; import '../logger.dart'; import '../mail/service.dart'; import 'model.dart'; part 'provider.g.dart'; /// Loads the contacts for the given [account] @Riverpod(keepAlive: true) Future<ContactManager> contactsLoader( ContactsLoaderRef ref, { required RealAccount account, }) async { final mailClient = EmailService.instance .createMailClient(account.mailAccount, account.name, null); try { await mailClient.connect(); final mailbox = await mailClient.selectMailboxByFlag(MailboxFlag.sent); if (mailbox.messagesExists > 0) { var startId = mailbox.messagesExists - 100; if (startId < 1) { startId = 1; } final sentMessages = await mailClient.fetchMessageSequence( MessageSequence.fromRangeToLast(startId), fetchPreference: FetchPreference.envelope, ); final addressesByEmail = <String, MailAddress>{}; for (final message in sentMessages) { _addAddresses(message.to, addressesByEmail); _addAddresses(message.cc, addressesByEmail); _addAddresses(message.bcc, addressesByEmail); } final manager = ContactManager(addressesByEmail.values.toList()); final updatedAccount = account.copyWith(contactManager: manager); ref.read(realAccountsProvider.notifier).replaceAccount( oldAccount: account, newAccount: updatedAccount, save: false, ); return manager; } } catch (e, s) { logger.e('unable to load sent messages: $e', error: e, stackTrace: s); } finally { await mailClient.disconnect(); } return ContactManager([]); } void _addAddresses( List<MailAddress>? addresses, Map<String, MailAddress> addressesByEmail, ) { if (addresses == null) { return; } for (final address in addresses) { final email = address.email.toLowerCase(); final existing = addressesByEmail[email]; if (existing == null || !existing.hasPersonalName) { addressesByEmail[email] = address; } } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/contact/contact.dart
export 'model.dart'; export 'provider.dart';
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/contact/model.dart
import 'package:enough_mail/enough_mail.dart'; /// Contains a list of a contacts for a given account class ContactManager { /// Creates a new [ContactManager] with the given [addresses ContactManager(this.addresses); /// The list of addresses final List<MailAddress> addresses; /// Finds the addresses matching the given [search] Iterable<MailAddress> find(String search) => addresses.where( (address) => address.email.contains(search) || (address.hasPersonalName && (address.personalName ?? '').contains(search)), ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/mail/provider.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'provider.dart'; // ************************************************************************** // RiverpodGenerator // ************************************************************************** String _$mailboxTreeHash() => r'2feafc0f0d00b8c4547b6408363a522539e85853'; /// Copied from Dart SDK class _SystemHash { _SystemHash._(); static int combine(int hash, int value) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + value); // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int finish(int hash) { // ignore: parameter_assignments hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); // ignore: parameter_assignments hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } } //// Loads the mailbox tree for the given account /// /// Copied from [mailboxTree]. @ProviderFor(mailboxTree) const mailboxTreeProvider = MailboxTreeFamily(); //// Loads the mailbox tree for the given account /// /// Copied from [mailboxTree]. class MailboxTreeFamily extends Family<AsyncValue<Tree<Mailbox?>>> { //// Loads the mailbox tree for the given account /// /// Copied from [mailboxTree]. const MailboxTreeFamily(); //// Loads the mailbox tree for the given account /// /// Copied from [mailboxTree]. MailboxTreeProvider call({ required Account account, }) { return MailboxTreeProvider( account: account, ); } @override MailboxTreeProvider getProviderOverride( covariant MailboxTreeProvider provider, ) { return call( account: provider.account, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'mailboxTreeProvider'; } //// Loads the mailbox tree for the given account /// /// Copied from [mailboxTree]. class MailboxTreeProvider extends FutureProvider<Tree<Mailbox?>> { //// Loads the mailbox tree for the given account /// /// Copied from [mailboxTree]. MailboxTreeProvider({ required Account account, }) : this._internal( (ref) => mailboxTree( ref as MailboxTreeRef, account: account, ), from: mailboxTreeProvider, name: r'mailboxTreeProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$mailboxTreeHash, dependencies: MailboxTreeFamily._dependencies, allTransitiveDependencies: MailboxTreeFamily._allTransitiveDependencies, account: account, ); MailboxTreeProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, }) : super.internal(); final Account account; @override Override overrideWith( FutureOr<Tree<Mailbox?>> Function(MailboxTreeRef provider) create, ) { return ProviderOverride( origin: this, override: MailboxTreeProvider._internal( (ref) => create(ref as MailboxTreeRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, ), ); } @override FutureProviderElement<Tree<Mailbox?>> createElement() { return _MailboxTreeProviderElement(this); } @override bool operator ==(Object other) { return other is MailboxTreeProvider && other.account == account; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); return _SystemHash.finish(hash); } } mixin MailboxTreeRef on FutureProviderRef<Tree<Mailbox?>> { /// The parameter `account` of this provider. Account get account; } class _MailboxTreeProviderElement extends FutureProviderElement<Tree<Mailbox?>> with MailboxTreeRef { _MailboxTreeProviderElement(super.provider); @override Account get account => (origin as MailboxTreeProvider).account; } String _$findMailboxHash() => r'fb113e28a8bb6904dbdd07a73898bc198afb2dda'; //// Loads the mailbox tree for the given account /// /// Copied from [findMailbox]. @ProviderFor(findMailbox) const findMailboxProvider = FindMailboxFamily(); //// Loads the mailbox tree for the given account /// /// Copied from [findMailbox]. class FindMailboxFamily extends Family<AsyncValue<Mailbox?>> { //// Loads the mailbox tree for the given account /// /// Copied from [findMailbox]. const FindMailboxFamily(); //// Loads the mailbox tree for the given account /// /// Copied from [findMailbox]. FindMailboxProvider call({ required Account account, required String encodedMailboxPath, }) { return FindMailboxProvider( account: account, encodedMailboxPath: encodedMailboxPath, ); } @override FindMailboxProvider getProviderOverride( covariant FindMailboxProvider provider, ) { return call( account: provider.account, encodedMailboxPath: provider.encodedMailboxPath, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'findMailboxProvider'; } //// Loads the mailbox tree for the given account /// /// Copied from [findMailbox]. class FindMailboxProvider extends AutoDisposeFutureProvider<Mailbox?> { //// Loads the mailbox tree for the given account /// /// Copied from [findMailbox]. FindMailboxProvider({ required Account account, required String encodedMailboxPath, }) : this._internal( (ref) => findMailbox( ref as FindMailboxRef, account: account, encodedMailboxPath: encodedMailboxPath, ), from: findMailboxProvider, name: r'findMailboxProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$findMailboxHash, dependencies: FindMailboxFamily._dependencies, allTransitiveDependencies: FindMailboxFamily._allTransitiveDependencies, account: account, encodedMailboxPath: encodedMailboxPath, ); FindMailboxProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.encodedMailboxPath, }) : super.internal(); final Account account; final String encodedMailboxPath; @override Override overrideWith( FutureOr<Mailbox?> Function(FindMailboxRef provider) create, ) { return ProviderOverride( origin: this, override: FindMailboxProvider._internal( (ref) => create(ref as FindMailboxRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, encodedMailboxPath: encodedMailboxPath, ), ); } @override AutoDisposeFutureProviderElement<Mailbox?> createElement() { return _FindMailboxProviderElement(this); } @override bool operator ==(Object other) { return other is FindMailboxProvider && other.account == account && other.encodedMailboxPath == encodedMailboxPath; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, encodedMailboxPath.hashCode); return _SystemHash.finish(hash); } } mixin FindMailboxRef on AutoDisposeFutureProviderRef<Mailbox?> { /// The parameter `account` of this provider. Account get account; /// The parameter `encodedMailboxPath` of this provider. String get encodedMailboxPath; } class _FindMailboxProviderElement extends AutoDisposeFutureProviderElement<Mailbox?> with FindMailboxRef { _FindMailboxProviderElement(super.provider); @override Account get account => (origin as FindMailboxProvider).account; @override String get encodedMailboxPath => (origin as FindMailboxProvider).encodedMailboxPath; } String _$mailSearchHash() => r'12e814bd6c0f53f6209dd0f68edf09a0ec769c8b'; /// Carries out a search for mail messages /// /// Copied from [mailSearch]. @ProviderFor(mailSearch) const mailSearchProvider = MailSearchFamily(); /// Carries out a search for mail messages /// /// Copied from [mailSearch]. class MailSearchFamily extends Family<AsyncValue<MessageSource>> { /// Carries out a search for mail messages /// /// Copied from [mailSearch]. const MailSearchFamily(); /// Carries out a search for mail messages /// /// Copied from [mailSearch]. MailSearchProvider call({ required AppLocalizations localizations, required MailSearch search, }) { return MailSearchProvider( localizations: localizations, search: search, ); } @override MailSearchProvider getProviderOverride( covariant MailSearchProvider provider, ) { return call( localizations: provider.localizations, search: provider.search, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'mailSearchProvider'; } /// Carries out a search for mail messages /// /// Copied from [mailSearch]. class MailSearchProvider extends AutoDisposeFutureProvider<MessageSource> { /// Carries out a search for mail messages /// /// Copied from [mailSearch]. MailSearchProvider({ required AppLocalizations localizations, required MailSearch search, }) : this._internal( (ref) => mailSearch( ref as MailSearchRef, localizations: localizations, search: search, ), from: mailSearchProvider, name: r'mailSearchProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$mailSearchHash, dependencies: MailSearchFamily._dependencies, allTransitiveDependencies: MailSearchFamily._allTransitiveDependencies, localizations: localizations, search: search, ); MailSearchProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.localizations, required this.search, }) : super.internal(); final AppLocalizations localizations; final MailSearch search; @override Override overrideWith( FutureOr<MessageSource> Function(MailSearchRef provider) create, ) { return ProviderOverride( origin: this, override: MailSearchProvider._internal( (ref) => create(ref as MailSearchRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, localizations: localizations, search: search, ), ); } @override AutoDisposeFutureProviderElement<MessageSource> createElement() { return _MailSearchProviderElement(this); } @override bool operator ==(Object other) { return other is MailSearchProvider && other.localizations == localizations && other.search == search; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, localizations.hashCode); hash = _SystemHash.combine(hash, search.hashCode); return _SystemHash.finish(hash); } } mixin MailSearchRef on AutoDisposeFutureProviderRef<MessageSource> { /// The parameter `localizations` of this provider. AppLocalizations get localizations; /// The parameter `search` of this provider. MailSearch get search; } class _MailSearchProviderElement extends AutoDisposeFutureProviderElement<MessageSource> with MailSearchRef { _MailSearchProviderElement(super.provider); @override AppLocalizations get localizations => (origin as MailSearchProvider).localizations; @override MailSearch get search => (origin as MailSearchProvider).search; } String _$singleMessageLoaderHash() => r'ec18c48ee5c6ad77cb303cfea02e959979b4c9ce'; /// Loads the message source for the given payload /// /// Copied from [singleMessageLoader]. @ProviderFor(singleMessageLoader) const singleMessageLoaderProvider = SingleMessageLoaderFamily(); /// Loads the message source for the given payload /// /// Copied from [singleMessageLoader]. class SingleMessageLoaderFamily extends Family<AsyncValue<Message>> { /// Loads the message source for the given payload /// /// Copied from [singleMessageLoader]. const SingleMessageLoaderFamily(); /// Loads the message source for the given payload /// /// Copied from [singleMessageLoader]. SingleMessageLoaderProvider call({ required MailNotificationPayload payload, }) { return SingleMessageLoaderProvider( payload: payload, ); } @override SingleMessageLoaderProvider getProviderOverride( covariant SingleMessageLoaderProvider provider, ) { return call( payload: provider.payload, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'singleMessageLoaderProvider'; } /// Loads the message source for the given payload /// /// Copied from [singleMessageLoader]. class SingleMessageLoaderProvider extends AutoDisposeFutureProvider<Message> { /// Loads the message source for the given payload /// /// Copied from [singleMessageLoader]. SingleMessageLoaderProvider({ required MailNotificationPayload payload, }) : this._internal( (ref) => singleMessageLoader( ref as SingleMessageLoaderRef, payload: payload, ), from: singleMessageLoaderProvider, name: r'singleMessageLoaderProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$singleMessageLoaderHash, dependencies: SingleMessageLoaderFamily._dependencies, allTransitiveDependencies: SingleMessageLoaderFamily._allTransitiveDependencies, payload: payload, ); SingleMessageLoaderProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.payload, }) : super.internal(); final MailNotificationPayload payload; @override Override overrideWith( FutureOr<Message> Function(SingleMessageLoaderRef provider) create, ) { return ProviderOverride( origin: this, override: SingleMessageLoaderProvider._internal( (ref) => create(ref as SingleMessageLoaderRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, payload: payload, ), ); } @override AutoDisposeFutureProviderElement<Message> createElement() { return _SingleMessageLoaderProviderElement(this); } @override bool operator ==(Object other) { return other is SingleMessageLoaderProvider && other.payload == payload; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, payload.hashCode); return _SystemHash.finish(hash); } } mixin SingleMessageLoaderRef on AutoDisposeFutureProviderRef<Message> { /// The parameter `payload` of this provider. MailNotificationPayload get payload; } class _SingleMessageLoaderProviderElement extends AutoDisposeFutureProviderElement<Message> with SingleMessageLoaderRef { _SingleMessageLoaderProviderElement(super.provider); @override MailNotificationPayload get payload => (origin as SingleMessageLoaderProvider).payload; } String _$firstTimeMailClientSourceHash() => r'ae11f3a5ed5cb6329488bd3f9ac3569ac8ad1f36'; /// Provides mail clients /// /// Copied from [firstTimeMailClientSource]. @ProviderFor(firstTimeMailClientSource) const firstTimeMailClientSourceProvider = FirstTimeMailClientSourceFamily(); /// Provides mail clients /// /// Copied from [firstTimeMailClientSource]. class FirstTimeMailClientSourceFamily extends Family<AsyncValue<ConnectedAccount?>> { /// Provides mail clients /// /// Copied from [firstTimeMailClientSource]. const FirstTimeMailClientSourceFamily(); /// Provides mail clients /// /// Copied from [firstTimeMailClientSource]. FirstTimeMailClientSourceProvider call({ required RealAccount account, Mailbox? mailbox, }) { return FirstTimeMailClientSourceProvider( account: account, mailbox: mailbox, ); } @override FirstTimeMailClientSourceProvider getProviderOverride( covariant FirstTimeMailClientSourceProvider provider, ) { return call( account: provider.account, mailbox: provider.mailbox, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'firstTimeMailClientSourceProvider'; } /// Provides mail clients /// /// Copied from [firstTimeMailClientSource]. class FirstTimeMailClientSourceProvider extends AutoDisposeFutureProvider<ConnectedAccount?> { /// Provides mail clients /// /// Copied from [firstTimeMailClientSource]. FirstTimeMailClientSourceProvider({ required RealAccount account, Mailbox? mailbox, }) : this._internal( (ref) => firstTimeMailClientSource( ref as FirstTimeMailClientSourceRef, account: account, mailbox: mailbox, ), from: firstTimeMailClientSourceProvider, name: r'firstTimeMailClientSourceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$firstTimeMailClientSourceHash, dependencies: FirstTimeMailClientSourceFamily._dependencies, allTransitiveDependencies: FirstTimeMailClientSourceFamily._allTransitiveDependencies, account: account, mailbox: mailbox, ); FirstTimeMailClientSourceProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.mailbox, }) : super.internal(); final RealAccount account; final Mailbox? mailbox; @override Override overrideWith( FutureOr<ConnectedAccount?> Function(FirstTimeMailClientSourceRef provider) create, ) { return ProviderOverride( origin: this, override: FirstTimeMailClientSourceProvider._internal( (ref) => create(ref as FirstTimeMailClientSourceRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, mailbox: mailbox, ), ); } @override AutoDisposeFutureProviderElement<ConnectedAccount?> createElement() { return _FirstTimeMailClientSourceProviderElement(this); } @override bool operator ==(Object other) { return other is FirstTimeMailClientSourceProvider && other.account == account && other.mailbox == mailbox; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, mailbox.hashCode); return _SystemHash.finish(hash); } } mixin FirstTimeMailClientSourceRef on AutoDisposeFutureProviderRef<ConnectedAccount?> { /// The parameter `account` of this provider. RealAccount get account; /// The parameter `mailbox` of this provider. Mailbox? get mailbox; } class _FirstTimeMailClientSourceProviderElement extends AutoDisposeFutureProviderElement<ConnectedAccount?> with FirstTimeMailClientSourceRef { _FirstTimeMailClientSourceProviderElement(super.provider); @override RealAccount get account => (origin as FirstTimeMailClientSourceProvider).account; @override Mailbox? get mailbox => (origin as FirstTimeMailClientSourceProvider).mailbox; } String _$mailtoHash() => r'392c1cf4d13bff03113b564193f1f1b21099cdac'; /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri /// /// Copied from [mailto]. @ProviderFor(mailto) const mailtoProvider = MailtoFamily(); /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri /// /// Copied from [mailto]. class MailtoFamily extends Family<MessageBuilder> { /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri /// /// Copied from [mailto]. const MailtoFamily(); /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri /// /// Copied from [mailto]. MailtoProvider call({ required Uri mailtoUri, required MimeMessage originatingMessage, }) { return MailtoProvider( mailtoUri: mailtoUri, originatingMessage: originatingMessage, ); } @override MailtoProvider getProviderOverride( covariant MailtoProvider provider, ) { return call( mailtoUri: provider.mailtoUri, originatingMessage: provider.originatingMessage, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'mailtoProvider'; } /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri /// /// Copied from [mailto]. class MailtoProvider extends AutoDisposeProvider<MessageBuilder> { /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri /// /// Copied from [mailto]. MailtoProvider({ required Uri mailtoUri, required MimeMessage originatingMessage, }) : this._internal( (ref) => mailto( ref as MailtoRef, mailtoUri: mailtoUri, originatingMessage: originatingMessage, ), from: mailtoProvider, name: r'mailtoProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$mailtoHash, dependencies: MailtoFamily._dependencies, allTransitiveDependencies: MailtoFamily._allTransitiveDependencies, mailtoUri: mailtoUri, originatingMessage: originatingMessage, ); MailtoProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.mailtoUri, required this.originatingMessage, }) : super.internal(); final Uri mailtoUri; final MimeMessage originatingMessage; @override Override overrideWith( MessageBuilder Function(MailtoRef provider) create, ) { return ProviderOverride( origin: this, override: MailtoProvider._internal( (ref) => create(ref as MailtoRef), from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, mailtoUri: mailtoUri, originatingMessage: originatingMessage, ), ); } @override AutoDisposeProviderElement<MessageBuilder> createElement() { return _MailtoProviderElement(this); } @override bool operator ==(Object other) { return other is MailtoProvider && other.mailtoUri == mailtoUri && other.originatingMessage == originatingMessage; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, mailtoUri.hashCode); hash = _SystemHash.combine(hash, originatingMessage.hashCode); return _SystemHash.finish(hash); } } mixin MailtoRef on AutoDisposeProviderRef<MessageBuilder> { /// The parameter `mailtoUri` of this provider. Uri get mailtoUri; /// The parameter `originatingMessage` of this provider. MimeMessage get originatingMessage; } class _MailtoProviderElement extends AutoDisposeProviderElement<MessageBuilder> with MailtoRef { _MailtoProviderElement(super.provider); @override Uri get mailtoUri => (origin as MailtoProvider).mailtoUri; @override MimeMessage get originatingMessage => (origin as MailtoProvider).originatingMessage; } String _$sourceHash() => r'd4e787d804ab333fbd5079af8a66fc5222bdef45'; abstract class _$Source extends BuildlessAsyncNotifier<MessageSource> { late final Account account; late final Mailbox? mailbox; Future<MessageSource> build({ required Account account, Mailbox? mailbox, }); } /// Provides the message source for the given account /// /// Copied from [Source]. @ProviderFor(Source) const sourceProvider = SourceFamily(); /// Provides the message source for the given account /// /// Copied from [Source]. class SourceFamily extends Family<AsyncValue<MessageSource>> { /// Provides the message source for the given account /// /// Copied from [Source]. const SourceFamily(); /// Provides the message source for the given account /// /// Copied from [Source]. SourceProvider call({ required Account account, Mailbox? mailbox, }) { return SourceProvider( account: account, mailbox: mailbox, ); } @override SourceProvider getProviderOverride( covariant SourceProvider provider, ) { return call( account: provider.account, mailbox: provider.mailbox, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'sourceProvider'; } /// Provides the message source for the given account /// /// Copied from [Source]. class SourceProvider extends AsyncNotifierProviderImpl<Source, MessageSource> { /// Provides the message source for the given account /// /// Copied from [Source]. SourceProvider({ required Account account, Mailbox? mailbox, }) : this._internal( () => Source() ..account = account ..mailbox = mailbox, from: sourceProvider, name: r'sourceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$sourceHash, dependencies: SourceFamily._dependencies, allTransitiveDependencies: SourceFamily._allTransitiveDependencies, account: account, mailbox: mailbox, ); SourceProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.mailbox, }) : super.internal(); final Account account; final Mailbox? mailbox; @override Future<MessageSource> runNotifierBuild( covariant Source notifier, ) { return notifier.build( account: account, mailbox: mailbox, ); } @override Override overrideWith(Source Function() create) { return ProviderOverride( origin: this, override: SourceProvider._internal( () => create() ..account = account ..mailbox = mailbox, from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, mailbox: mailbox, ), ); } @override AsyncNotifierProviderElement<Source, MessageSource> createElement() { return _SourceProviderElement(this); } @override bool operator ==(Object other) { return other is SourceProvider && other.account == account && other.mailbox == mailbox; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, mailbox.hashCode); return _SystemHash.finish(hash); } } mixin SourceRef on AsyncNotifierProviderRef<MessageSource> { /// The parameter `account` of this provider. Account get account; /// The parameter `mailbox` of this provider. Mailbox? get mailbox; } class _SourceProviderElement extends AsyncNotifierProviderElement<Source, MessageSource> with SourceRef { _SourceProviderElement(super.provider); @override Account get account => (origin as SourceProvider).account; @override Mailbox? get mailbox => (origin as SourceProvider).mailbox; } String _$unifiedSourceHash() => r'9b128c1a2afaa51fa11e0810a9e6ecddfc6c53fd'; abstract class _$UnifiedSource extends BuildlessAsyncNotifier<MultipleMessageSource> { late final UnifiedAccount account; late final Mailbox? mailbox; Future<MultipleMessageSource> build({ required UnifiedAccount account, Mailbox? mailbox, }); } /// Provides the message source for the given account /// /// Copied from [UnifiedSource]. @ProviderFor(UnifiedSource) const unifiedSourceProvider = UnifiedSourceFamily(); /// Provides the message source for the given account /// /// Copied from [UnifiedSource]. class UnifiedSourceFamily extends Family<AsyncValue<MultipleMessageSource>> { /// Provides the message source for the given account /// /// Copied from [UnifiedSource]. const UnifiedSourceFamily(); /// Provides the message source for the given account /// /// Copied from [UnifiedSource]. UnifiedSourceProvider call({ required UnifiedAccount account, Mailbox? mailbox, }) { return UnifiedSourceProvider( account: account, mailbox: mailbox, ); } @override UnifiedSourceProvider getProviderOverride( covariant UnifiedSourceProvider provider, ) { return call( account: provider.account, mailbox: provider.mailbox, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'unifiedSourceProvider'; } /// Provides the message source for the given account /// /// Copied from [UnifiedSource]. class UnifiedSourceProvider extends AsyncNotifierProviderImpl<UnifiedSource, MultipleMessageSource> { /// Provides the message source for the given account /// /// Copied from [UnifiedSource]. UnifiedSourceProvider({ required UnifiedAccount account, Mailbox? mailbox, }) : this._internal( () => UnifiedSource() ..account = account ..mailbox = mailbox, from: unifiedSourceProvider, name: r'unifiedSourceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$unifiedSourceHash, dependencies: UnifiedSourceFamily._dependencies, allTransitiveDependencies: UnifiedSourceFamily._allTransitiveDependencies, account: account, mailbox: mailbox, ); UnifiedSourceProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.mailbox, }) : super.internal(); final UnifiedAccount account; final Mailbox? mailbox; @override Future<MultipleMessageSource> runNotifierBuild( covariant UnifiedSource notifier, ) { return notifier.build( account: account, mailbox: mailbox, ); } @override Override overrideWith(UnifiedSource Function() create) { return ProviderOverride( origin: this, override: UnifiedSourceProvider._internal( () => create() ..account = account ..mailbox = mailbox, from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, mailbox: mailbox, ), ); } @override AsyncNotifierProviderElement<UnifiedSource, MultipleMessageSource> createElement() { return _UnifiedSourceProviderElement(this); } @override bool operator ==(Object other) { return other is UnifiedSourceProvider && other.account == account && other.mailbox == mailbox; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, mailbox.hashCode); return _SystemHash.finish(hash); } } mixin UnifiedSourceRef on AsyncNotifierProviderRef<MultipleMessageSource> { /// The parameter `account` of this provider. UnifiedAccount get account; /// The parameter `mailbox` of this provider. Mailbox? get mailbox; } class _UnifiedSourceProviderElement extends AsyncNotifierProviderElement<UnifiedSource, MultipleMessageSource> with UnifiedSourceRef { _UnifiedSourceProviderElement(super.provider); @override UnifiedAccount get account => (origin as UnifiedSourceProvider).account; @override Mailbox? get mailbox => (origin as UnifiedSourceProvider).mailbox; } String _$realSourceHash() => r'b47b7d957d62f73be40a5e8666d7f5c76209e502'; abstract class _$RealSource extends BuildlessAsyncNotifier<MailboxMessageSource> { late final RealAccount account; late final Mailbox? mailbox; Future<MailboxMessageSource> build({ required RealAccount account, Mailbox? mailbox, }); } /// Provides the message source for the given account /// /// Copied from [RealSource]. @ProviderFor(RealSource) const realSourceProvider = RealSourceFamily(); /// Provides the message source for the given account /// /// Copied from [RealSource]. class RealSourceFamily extends Family<AsyncValue<MailboxMessageSource>> { /// Provides the message source for the given account /// /// Copied from [RealSource]. const RealSourceFamily(); /// Provides the message source for the given account /// /// Copied from [RealSource]. RealSourceProvider call({ required RealAccount account, Mailbox? mailbox, }) { return RealSourceProvider( account: account, mailbox: mailbox, ); } @override RealSourceProvider getProviderOverride( covariant RealSourceProvider provider, ) { return call( account: provider.account, mailbox: provider.mailbox, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'realSourceProvider'; } /// Provides the message source for the given account /// /// Copied from [RealSource]. class RealSourceProvider extends AsyncNotifierProviderImpl<RealSource, MailboxMessageSource> { /// Provides the message source for the given account /// /// Copied from [RealSource]. RealSourceProvider({ required RealAccount account, Mailbox? mailbox, }) : this._internal( () => RealSource() ..account = account ..mailbox = mailbox, from: realSourceProvider, name: r'realSourceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$realSourceHash, dependencies: RealSourceFamily._dependencies, allTransitiveDependencies: RealSourceFamily._allTransitiveDependencies, account: account, mailbox: mailbox, ); RealSourceProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.mailbox, }) : super.internal(); final RealAccount account; final Mailbox? mailbox; @override Future<MailboxMessageSource> runNotifierBuild( covariant RealSource notifier, ) { return notifier.build( account: account, mailbox: mailbox, ); } @override Override overrideWith(RealSource Function() create) { return ProviderOverride( origin: this, override: RealSourceProvider._internal( () => create() ..account = account ..mailbox = mailbox, from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, mailbox: mailbox, ), ); } @override AsyncNotifierProviderElement<RealSource, MailboxMessageSource> createElement() { return _RealSourceProviderElement(this); } @override bool operator ==(Object other) { return other is RealSourceProvider && other.account == account && other.mailbox == mailbox; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, mailbox.hashCode); return _SystemHash.finish(hash); } } mixin RealSourceRef on AsyncNotifierProviderRef<MailboxMessageSource> { /// The parameter `account` of this provider. RealAccount get account; /// The parameter `mailbox` of this provider. Mailbox? get mailbox; } class _RealSourceProviderElement extends AsyncNotifierProviderElement<RealSource, MailboxMessageSource> with RealSourceRef { _RealSourceProviderElement(super.provider); @override RealAccount get account => (origin as RealSourceProvider).account; @override Mailbox? get mailbox => (origin as RealSourceProvider).mailbox; } String _$realMimeSourceHash() => r'4c50962bb20d8eacf3a69062ae2a656627393dcb'; abstract class _$RealMimeSource extends BuildlessAsyncNotifier<AsyncMimeSource> { late final RealAccount account; late final Mailbox? mailbox; Future<AsyncMimeSource> build({ required RealAccount account, Mailbox? mailbox, }); } /// Provides the message source for the given account /// /// Copied from [RealMimeSource]. @ProviderFor(RealMimeSource) const realMimeSourceProvider = RealMimeSourceFamily(); /// Provides the message source for the given account /// /// Copied from [RealMimeSource]. class RealMimeSourceFamily extends Family<AsyncValue<AsyncMimeSource>> { /// Provides the message source for the given account /// /// Copied from [RealMimeSource]. const RealMimeSourceFamily(); /// Provides the message source for the given account /// /// Copied from [RealMimeSource]. RealMimeSourceProvider call({ required RealAccount account, Mailbox? mailbox, }) { return RealMimeSourceProvider( account: account, mailbox: mailbox, ); } @override RealMimeSourceProvider getProviderOverride( covariant RealMimeSourceProvider provider, ) { return call( account: provider.account, mailbox: provider.mailbox, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'realMimeSourceProvider'; } /// Provides the message source for the given account /// /// Copied from [RealMimeSource]. class RealMimeSourceProvider extends AsyncNotifierProviderImpl<RealMimeSource, AsyncMimeSource> { /// Provides the message source for the given account /// /// Copied from [RealMimeSource]. RealMimeSourceProvider({ required RealAccount account, Mailbox? mailbox, }) : this._internal( () => RealMimeSource() ..account = account ..mailbox = mailbox, from: realMimeSourceProvider, name: r'realMimeSourceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$realMimeSourceHash, dependencies: RealMimeSourceFamily._dependencies, allTransitiveDependencies: RealMimeSourceFamily._allTransitiveDependencies, account: account, mailbox: mailbox, ); RealMimeSourceProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.mailbox, }) : super.internal(); final RealAccount account; final Mailbox? mailbox; @override Future<AsyncMimeSource> runNotifierBuild( covariant RealMimeSource notifier, ) { return notifier.build( account: account, mailbox: mailbox, ); } @override Override overrideWith(RealMimeSource Function() create) { return ProviderOverride( origin: this, override: RealMimeSourceProvider._internal( () => create() ..account = account ..mailbox = mailbox, from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, mailbox: mailbox, ), ); } @override AsyncNotifierProviderElement<RealMimeSource, AsyncMimeSource> createElement() { return _RealMimeSourceProviderElement(this); } @override bool operator ==(Object other) { return other is RealMimeSourceProvider && other.account == account && other.mailbox == mailbox; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, mailbox.hashCode); return _SystemHash.finish(hash); } } mixin RealMimeSourceRef on AsyncNotifierProviderRef<AsyncMimeSource> { /// The parameter `account` of this provider. RealAccount get account; /// The parameter `mailbox` of this provider. Mailbox? get mailbox; } class _RealMimeSourceProviderElement extends AsyncNotifierProviderElement<RealMimeSource, AsyncMimeSource> with RealMimeSourceRef { _RealMimeSourceProviderElement(super.provider); @override RealAccount get account => (origin as RealMimeSourceProvider).account; @override Mailbox? get mailbox => (origin as RealMimeSourceProvider).mailbox; } String _$mailClientSourceHash() => r'6245fdaddaceb72c43b94b988b7e6dfd5966c8ab'; abstract class _$MailClientSource extends BuildlessNotifier<MailClient> { late final RealAccount account; late final Mailbox? mailbox; MailClient build({ required RealAccount account, Mailbox? mailbox, }); } /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. /// /// Copied from [MailClientSource]. @ProviderFor(MailClientSource) const mailClientSourceProvider = MailClientSourceFamily(); /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. /// /// Copied from [MailClientSource]. class MailClientSourceFamily extends Family<MailClient> { /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. /// /// Copied from [MailClientSource]. const MailClientSourceFamily(); /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. /// /// Copied from [MailClientSource]. MailClientSourceProvider call({ required RealAccount account, Mailbox? mailbox, }) { return MailClientSourceProvider( account: account, mailbox: mailbox, ); } @override MailClientSourceProvider getProviderOverride( covariant MailClientSourceProvider provider, ) { return call( account: provider.account, mailbox: provider.mailbox, ); } static const Iterable<ProviderOrFamily>? _dependencies = null; @override Iterable<ProviderOrFamily>? get dependencies => _dependencies; static const Iterable<ProviderOrFamily>? _allTransitiveDependencies = null; @override Iterable<ProviderOrFamily>? get allTransitiveDependencies => _allTransitiveDependencies; @override String? get name => r'mailClientSourceProvider'; } /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. /// /// Copied from [MailClientSource]. class MailClientSourceProvider extends NotifierProviderImpl<MailClientSource, MailClient> { /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. /// /// Copied from [MailClientSource]. MailClientSourceProvider({ required RealAccount account, Mailbox? mailbox, }) : this._internal( () => MailClientSource() ..account = account ..mailbox = mailbox, from: mailClientSourceProvider, name: r'mailClientSourceProvider', debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product') ? null : _$mailClientSourceHash, dependencies: MailClientSourceFamily._dependencies, allTransitiveDependencies: MailClientSourceFamily._allTransitiveDependencies, account: account, mailbox: mailbox, ); MailClientSourceProvider._internal( super._createNotifier, { required super.name, required super.dependencies, required super.allTransitiveDependencies, required super.debugGetCreateSourceHash, required super.from, required this.account, required this.mailbox, }) : super.internal(); final RealAccount account; final Mailbox? mailbox; @override MailClient runNotifierBuild( covariant MailClientSource notifier, ) { return notifier.build( account: account, mailbox: mailbox, ); } @override Override overrideWith(MailClientSource Function() create) { return ProviderOverride( origin: this, override: MailClientSourceProvider._internal( () => create() ..account = account ..mailbox = mailbox, from: from, name: null, dependencies: null, allTransitiveDependencies: null, debugGetCreateSourceHash: null, account: account, mailbox: mailbox, ), ); } @override NotifierProviderElement<MailClientSource, MailClient> createElement() { return _MailClientSourceProviderElement(this); } @override bool operator ==(Object other) { return other is MailClientSourceProvider && other.account == account && other.mailbox == mailbox; } @override int get hashCode { var hash = _SystemHash.combine(0, runtimeType.hashCode); hash = _SystemHash.combine(hash, account.hashCode); hash = _SystemHash.combine(hash, mailbox.hashCode); return _SystemHash.finish(hash); } } mixin MailClientSourceRef on NotifierProviderRef<MailClient> { /// The parameter `account` of this provider. RealAccount get account; /// The parameter `mailbox` of this provider. Mailbox? get mailbox; } class _MailClientSourceProviderElement extends NotifierProviderElement<MailClientSource, MailClient> with MailClientSourceRef { _MailClientSourceProviderElement(super.provider); @override RealAccount get account => (origin as MailClientSourceProvider).account; @override Mailbox? get mailbox => (origin as MailClientSourceProvider).mailbox; } // ignore_for_file: type=lint // ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/mail/service.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:flutter/foundation.dart'; import '../account/model.dart'; import '../hoster/service.dart'; import '../models/async_mime_source.dart'; import '../models/async_mime_source_factory.dart'; /// Callback when the configuration of a mail client has changed, /// typically when the OAuth token has been refreshed typedef OnMailClientConfigChanged = Future<void> Function(MailAccount account); /// Abstracts interaction and creation of mail clients / mime sources class EmailService { EmailService._(); static final _instance = EmailService._(); /// Retrieves the singleton instance static EmailService get instance => _instance; /// The used mime source factory static AsyncMimeSourceFactory mimeSourceFactory = const AsyncMimeSourceFactory(isOfflineModeSupported: false); static const _clientId = Id(name: 'Maily', version: '1.0'); /// Creates a mime source for the given account Future<AsyncMimeSource> createMimeSource({ required MailClient mailClient, Mailbox? mailbox, }) async { await mailClient.connect(); if (mailbox == null) { mailbox = await mailClient.selectInbox(); } else { await mailClient.selectMailbox(mailbox); } final source = mimeSourceFactory.createMailboxMimeSource( mailClient, mailbox, ); return source; } /// Creates a mail client for the given account MailClient createMailClient( MailAccount mailAccount, String logName, OnMailClientConfigChanged? onMailClientConfigChanged, ) { final bool isLogEnabled = kDebugMode || (mailAccount.attributes[RealAccount.attributeEnableLogging] ?? false); return MailClient( mailAccount, isLogEnabled: isLogEnabled, logName: logName, clientId: _clientId, refresh: _refreshToken, onConfigChanged: onMailClientConfigChanged, downloadSizeLimit: 32 * 1024, ); } Future<OauthToken?> _refreshToken( MailClient mailClient, OauthToken expiredToken, ) { final providerId = expiredToken.provider; if (providerId == null) { throw MailException( mailClient, 'no provider registered for token $expiredToken', ); } // TODO(RV): replace mail hoster service with a riverpod provider final provider = MailHosterService.instance[providerId]; if (provider == null) { throw MailException( mailClient, 'no provider "$providerId" found - token: $expiredToken', ); } final oauthClient = provider.oauthClient; if (oauthClient == null || !oauthClient.isEnabled) { throw MailException( mailClient, 'provider $providerId has no valid OAuth configuration', ); } return oauthClient.refresh(expiredToken); } /// Connects a MailAccount. /// /// Adapts the authentication user name if necessary Future<ConnectedAccount?> connectFirstTime( MailAccount mailAccount, OnMailClientConfigChanged? onMailClientConfigChanged, ) async { var usedMailAccount = mailAccount; var mailClient = createMailClient( usedMailAccount, mailAccount.name, onMailClientConfigChanged, ); try { await mailClient.connect(timeout: const Duration(seconds: 30)); } on MailException { await mailClient.disconnect(); final email = usedMailAccount.email; var preferredUserName = usedMailAccount.incoming.serverConfig.getUserName(email); if (preferredUserName == null || preferredUserName == email) { final atIndex = mailAccount.email.lastIndexOf('@'); preferredUserName = usedMailAccount.email.substring(0, atIndex); usedMailAccount = usedMailAccount.copyWithAuthenticationUserName(preferredUserName); await mailClient.disconnect(); mailClient = createMailClient( usedMailAccount, mailAccount.name, onMailClientConfigChanged, ); try { await mailClient.connect(timeout: const Duration(seconds: 30)); } on MailException { await mailClient.disconnect(); return null; } } } return ConnectedAccount(usedMailAccount, mailClient); } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/mail/provider.dart
import 'package:collection/collection.dart'; import 'package:enough_mail/enough_mail.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../account/model.dart'; import '../account/provider.dart'; import '../app_lifecycle/provider.dart'; import '../localization/app_localizations.g.dart'; import '../logger.dart'; import '../models/async_mime_source.dart'; import '../models/message.dart'; import '../models/message_source.dart'; import '../notification/model.dart'; import '../notification/service.dart'; import '../settings/provider.dart'; import 'service.dart'; part 'provider.g.dart'; /// Provides the message source for the given account @Riverpod(keepAlive: true) class Source extends _$Source { @override Future<MessageSource> build({ required Account account, Mailbox? mailbox, }) { Future.delayed(const Duration(milliseconds: 10)).then( (_) => ref.read(currentMailboxProvider.notifier).state = mailbox, ); final usedMailbox = mailbox?.isInbox ?? true ? null : mailbox; if (account is RealAccount) { return ref.watch( realSourceProvider(account: account, mailbox: usedMailbox).future, ); } if (account is UnifiedAccount) { return ref.watch( unifiedSourceProvider(account: account, mailbox: usedMailbox).future, ); } throw UnimplementedError('for account $account'); } } /// Provides the message source for the given account @Riverpod(keepAlive: true) class UnifiedSource extends _$UnifiedSource { @override Future<MultipleMessageSource> build({ required UnifiedAccount account, Mailbox? mailbox, }) async { logger.d( 'Creating unified source for ${account.key}: ' '${mailbox?.name ?? '<inbox>'}', ); Future<AsyncMimeSource?> resolve( RealAccount realAccount, Mailbox? mailbox, ) async { try { var usedMailbox = mailbox; final flag = mailbox?.identityFlag; if (mailbox != null && mailbox.isVirtual && flag != null) { final mailboxTree = await ref.watch( mailboxTreeProvider(account: realAccount).future, ); usedMailbox = mailboxTree.firstWhereOrNull( (m) => m?.flags.contains(flag) ?? false, ); } if (usedMailbox != null && usedMailbox.isInbox) { usedMailbox = null; } final source = await ref.watch( realMimeSourceProvider( account: realAccount, mailbox: usedMailbox, ).future, ); return source; } catch (e) { logger.e('Error loading source for ${realAccount.name}', error: e); return null; } } final accounts = account.accounts; final futureSources = accounts.map( (a) => resolve(a, mailbox), ); final mimeSourcesWithNullValues = await Future.wait(futureSources); final mimeSources = mimeSourcesWithNullValues.whereNotNull().toList(); if (mimeSources.isEmpty) { throw Exception('No mime sources could be connected'); } return MultipleMessageSource( mimeSources, account.name, mailbox?.identityFlag ?? MailboxFlag.inbox, account: account, ); } } /// Provides the message source for the given account @Riverpod(keepAlive: true) class RealSource extends _$RealSource { @override Future<MailboxMessageSource> build({ required RealAccount account, Mailbox? mailbox, }) async { logger.d( 'Creating message source for ${account.key}: ' '${mailbox?.name ?? '<inbox>'}', ); final source = await ref.watch( realMimeSourceProvider(account: account, mailbox: mailbox).future, ); return MailboxMessageSource.fromMimeSource( source, account.email, mailbox ?? source.mailbox, account: account, ); } } //// Loads the mailbox tree for the given account @Riverpod(keepAlive: true) Future<Tree<Mailbox?>> mailboxTree( MailboxTreeRef ref, { required Account account, }) async { logger.d('Creating mailbox tree for ${account.key}'); if (account is RealAccount) { final source = await ref.watch(realSourceProvider(account: account).future); return source.mimeSource.mailClient .listMailboxesAsTree(createIntermediate: false); } else if (account is UnifiedAccount) { final mailboxes = [ MailboxFlag.inbox, MailboxFlag.drafts, MailboxFlag.sent, MailboxFlag.trash, MailboxFlag.archive, MailboxFlag.junk, ].map((f) => Mailbox.virtual(f.name, [f])).toList(); return Tree<Mailbox?>(Mailbox.virtual('', [])) ..populateFromList(mailboxes, (child) => null); } else { throw UnimplementedError('for account $account'); } } //// Loads the mailbox tree for the given account @riverpod Future<Mailbox?> findMailbox( FindMailboxRef ref, { required Account account, required String encodedMailboxPath, }) async { final tree = await ref.watch(mailboxTreeProvider(account: account).future); final mailbox = tree.firstWhereOrNull((m) => m?.encodedPath == encodedMailboxPath); return mailbox; } /// Provides the message source for the given account @Riverpod(keepAlive: true) class RealMimeSource extends _$RealMimeSource implements MimeSourceSubscriber { @override Future<AsyncMimeSource> build({ required RealAccount account, Mailbox? mailbox, }) async { final usedMailboxForMailClient = (mailbox?.isInbox ?? true) ? null : mailbox; logger.d( 'Creating real mime source for ${account.key}: ' '${mailbox?.name ?? '<inbox>'}', ); final mailClient = ref.watch( mailClientSourceProvider( account: account, mailbox: usedMailboxForMailClient, ), ); try { final mimeSource = await EmailService.instance.createMimeSource( mailClient: mailClient, mailbox: mailbox, ); if (mailbox == null || mailbox.isInbox) { mimeSource.addSubscriber(this); } return mimeSource; } catch (e, s) { logger.e( 'Error creating mime source for ${account.key}', error: e, stackTrace: s, ); account.hasError = true; rethrow; } } @override void onMailArrived( MimeMessage mime, AsyncMimeSource source, { int index = 0, }) { if (source == state.value) { source.mailClient.lowLevelIncomingMailClient .logApp('new message: ${mime.decodeSubject()}'); if (!mime.isSeen && source.isInbox) { NotificationService.instance.sendLocalNotificationForMail( mime, source.mailClient.account.email, ); } } } @override void onMailCacheInvalidated(AsyncMimeSource source) { // ignore } @override void onMailFlagsUpdated(MimeMessage mime, AsyncMimeSource source) { if (mime.isSeen) { NotificationService.instance.cancelNotificationForMime(mime); } } @override void onMailVanished(MimeMessage mime, AsyncMimeSource source) { NotificationService.instance.cancelNotificationForMime(mime); } } /// Provides mail clients /// /// Expects [Mailbox] to be `null` for the inbox. @Riverpod(keepAlive: true) class MailClientSource extends _$MailClientSource { MailClient? _existingClient; @override MailClient build({ required RealAccount account, Mailbox? mailbox, }) { MailClient create() { final logName = mailbox != null ? '${account.name}-${mailbox.name}' : account.name; logger.d('Creating MailClient $logName'); return EmailService.instance.createMailClient( account.mailAccount, logName, (mailAccount) => ref .watch(realAccountsProvider.notifier) .updateMailAccount(account, mailAccount), ); } final isResumed = ref.watch(appIsResumedProvider); final client = _existingClient ?? create(); final existingClient = _existingClient; if (existingClient != null) { if (isResumed) { existingClient.resume(); } } else { _existingClient = client; } return client; } /// Creates a new mailbox with the given [mailboxName] Future<void> createMailbox( String mailboxName, Mailbox? parentMailbox, ) async { final mailClient = state; await mailClient.createMailbox(mailboxName, parentMailbox: parentMailbox); return ref.refresh(mailboxTreeProvider(account: account)); } /// Deletes the given [mailbox] Future<void> deleteMailbox(Mailbox mailbox) async { final mailClient = state; await mailClient.deleteMailbox(mailbox); return ref.refresh(mailboxTreeProvider(account: account)); } } /// Carries out a search for mail messages @riverpod Future<MessageSource> mailSearch( MailSearchRef ref, { required AppLocalizations localizations, required MailSearch search, }) async { final account = ref.watch(currentAccountProvider) ?? ref.watch(allAccountsProvider).first; final source = await ref.watch(sourceProvider(account: account).future); return source.search(localizations, search); } /// Loads the message source for the given payload @riverpod Future<Message> singleMessageLoader( SingleMessageLoaderRef ref, { required MailNotificationPayload payload, }) async { final account = ref.watch( findAccountByEmailProvider(email: payload.accountEmail), ); if (account == null) { throw Exception('Account not found for ${payload.accountEmail}'); } final source = await ref.watch(sourceProvider(account: account).future); return source.loadSingleMessage(payload); } /// Provides mail clients @riverpod Future<ConnectedAccount?> firstTimeMailClientSource( FirstTimeMailClientSourceRef ref, { required RealAccount account, Mailbox? mailbox, }) => EmailService.instance.connectFirstTime( account.mailAccount, (mailAccount) => ref .watch(realAccountsProvider.notifier) .updateMailAccount(account, mailAccount), ); /// Creates a new [MessageBuilder] based on the given [mailtoUri] uri @riverpod MessageBuilder mailto( MailtoRef ref, { required Uri mailtoUri, required MimeMessage originatingMessage, }) { final settings = ref.watch(settingsProvider); final senders = ref.watch(sendersProvider); final searchFor = senders.map((s) => s.address).toList(); final searchIn = originatingMessage.recipientAddresses .map((email) => MailAddress('', email)) .toList(); var fromAddress = MailAddress.getMatch(searchFor, searchIn); if (fromAddress == null) { if (settings.preferredComposeMailAddress != null) { fromAddress = searchFor.firstWhereOrNull( (address) => address.email == settings.preferredComposeMailAddress, ); } fromAddress ??= searchFor.first; } return MessageBuilder.prepareMailtoBasedMessage(mailtoUri, fromAddress); } /// Provides the locally current active mailbox final currentMailboxProvider = StateProvider<Mailbox?>((ref) => null);
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/mail/model.dart
import 'package:enough_mail/enough_mail.dart'; import '../localization/app_localizations.g.dart'; import '../models/message_source.dart'; import '../settings/model.dart'; /// Retrieves the localized name for the given mailbox flag extension _MailboxFlagExtensions on MailboxFlag { /// Retrieves the localized name for the given mailbox flag String localizedName( AppLocalizations localizations, Settings settings, Mailbox? mailbox, ) { final identityFlag = this; final folderNameSetting = settings.folderNameSetting; final isVirtual = mailbox?.isVirtual ?? true; switch (folderNameSetting) { case FolderNameSetting.server: return mailbox?.name ?? name; case FolderNameSetting.localized: switch (identityFlag) { case MailboxFlag.inbox: return isVirtual ? localizations.unifiedFolderInbox : localizations.folderInbox; case MailboxFlag.drafts: return isVirtual ? localizations.unifiedFolderDrafts : localizations.folderDrafts; case MailboxFlag.sent: return isVirtual ? localizations.unifiedFolderSent : localizations.folderSent; case MailboxFlag.trash: return isVirtual ? localizations.unifiedFolderTrash : localizations.folderTrash; case MailboxFlag.archive: return isVirtual ? localizations.unifiedFolderArchive : localizations.folderArchive; case MailboxFlag.junk: return isVirtual ? localizations.unifiedFolderJunk : localizations.folderJunk; // ignore: no_default_cases default: return mailbox?.name ?? name; } case FolderNameSetting.custom: final customNames = settings.customFolderNames ?? (isVirtual ? [ localizations.unifiedFolderInbox, localizations.unifiedFolderDrafts, localizations.unifiedFolderSent, localizations.unifiedFolderTrash, localizations.unifiedFolderArchive, localizations.unifiedFolderJunk, ] : [ localizations.folderInbox, localizations.folderDrafts, localizations.folderSent, localizations.folderTrash, localizations.folderArchive, localizations.folderJunk, ]); switch (identityFlag) { case MailboxFlag.inbox: return customNames[0]; case MailboxFlag.drafts: return customNames[1]; case MailboxFlag.sent: return customNames[2]; case MailboxFlag.trash: return customNames[3]; case MailboxFlag.archive: return customNames[4]; case MailboxFlag.junk: return customNames[5]; // ignore: no_default_cases default: return mailbox?.name ?? name; } } } } /// Allows to translate mailbox names extension MailboxExtensions on Mailbox { /// Retrieves the translated name String localizedName(AppLocalizations localizations, Settings settings) => identityFlag?.localizedName(localizations, settings, this) ?? name; } /// Allows to translate mailbox names extension MessageSourceExtensions on MessageSource { /// Retrieves the translated name String localizedName(AppLocalizations localizations, Settings settings) { final source = this; if (source is MailboxMessageSource) { return source.mailbox.localizedName(localizations, settings); } if (source is MultipleMessageSource) { return source.flag.localizedName(localizations, settings, null); } return source.name ?? source.parentName ?? localizations.folderUnknown; } }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/hoster/service.dart
import 'package:enough_mail/discover.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../localization/extension.dart'; import '../oauth/oauth.dart'; /// Allows to resolve mail-hoster specific settings like Oauth. class MailHosterService { MailHosterService._() { addAll([ GmailMailHoster(), OutlookMailHoster(), YahooMailHoster(), AolMailHoster(), AppleMailHoster(), GmxMailHoster(), MailboxOrMailHoster(), ]); } static final _instance = MailHosterService._(); /// Retrieves access to the singleton instance static MailHosterService get instance => _instance; final _providersByDomains = <String, MailHoster>{}; final _providers = <MailHoster>[]; /// Retrieves the supported hosters List<MailHoster> get hosters => _providers; /// Retrieves the provider for the given [incomingHostName] MailHoster? operator [](String incomingHostName) => _providersByDomains[incomingHostName]; /// Discovers a hoster by the given [email] Future<MailHoster?> discover(String email) async { final emailDomain = email.substring(email.indexOf('@') + 1); final providerEmail = _providersByDomains[emailDomain]; if (providerEmail != null) { return providerEmail; } try { final clientConfig = await Discover.discover( email, forceSslConnection: true, isLogEnabled: true, ); if (clientConfig == null || clientConfig.preferredIncomingServer == null) { return null; } final hostName = clientConfig.preferredIncomingServer?.hostname ?? ''; final providerHostName = _providersByDomains[hostName]; if (providerHostName != null) { return providerHostName; } final id = email.substring(email.indexOf('@') + 1); return MailHoster(id, hostName, clientConfig); } catch (e, s) { if (kDebugMode) { print('Unable to discover settings for [$email]: $e $s'); } return null; } } void addAll(Iterable<MailHoster> providers) { providers.forEach(add); } void add(MailHoster provider) { _providers.add(provider); _providersByDomains[provider.incomingHostName] = provider; final domains = provider.domains; if (domains != null) { for (final domain in domains) { _providersByDomains[domain] = provider; } } } } /// Provides access information about a mail hoster class MailHoster { /// Creates a new [MailHoster] const MailHoster( this.key, this.incomingHostName, this.clientConfig, { this.oauthClient, this.appSpecificPasswordSetupUrl, this.manualImapAccessSetupUrl, this.domains, }); /// The key of the mail hoster, help to resolves image resources and /// possibly other settings like branding guidelines final String key; final String incomingHostName; final ClientConfig clientConfig; final OauthClient? oauthClient; bool get hasOAuthClient { final oauthClient = this.oauthClient; return oauthClient != null && oauthClient.isEnabled; } final String? appSpecificPasswordSetupUrl; final String? manualImapAccessSetupUrl; final List<String>? domains; String? get displayName { final emailProviders = clientConfig.emailProviders; return (emailProviders == null || emailProviders.isEmpty) ? null : emailProviders.first.displayName; } /// Builds the sign in button for this provider /// /// As this is UI, consider moving to a widget extension class? Widget buildSignInButton( WidgetRef ref, { required Function() onPressed, bool isSignInButton = false, }) { final localizations = ref.text; final providerName = displayName ?? '<unknown>'; final buttonText = isSignInButton ? localizations.addAccountOauthSignIn(providerName) : providerName; return Theme( data: ThemeData(brightness: Brightness.light), child: PlatformTextButton( onPressed: onPressed, child: Container( decoration: const BoxDecoration( color: Colors.white, ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: Row( mainAxisSize: MainAxisSize.min, children: [ Image.asset( 'assets/images/providers/$key.png', height: 50, fit: BoxFit.contain, errorBuilder: (context, error, stacktrace) => Container(), package: 'enough_mail_app', ), Padding( padding: const EdgeInsets.symmetric(horizontal: 8), child: Text(buttonText), ), ], ), ), ), ), ); } } class GmailMailHoster extends MailHoster { GmailMailHoster() : super( 'gmail', 'imap.gmail.com', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'Google Mail', displayShortName: 'Gmail', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'imap.gmail.com', port: 993, socketType: SocketType.ssl, authentication: Authentication.oauth2, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'smtp.gmail.com', port: 465, socketType: SocketType.ssl, authentication: Authentication.oauth2, usernameType: UsernameType.emailAddress, ), ], ), ], appSpecificPasswordSetupUrl: 'https://support.google.com/accounts/answer/185833', domains: ['gmail.com', 'googlemail.com', 'google.com', 'jazztel.es'], oauthClient: GmailOAuthClient(), ); @override Widget buildSignInButton( WidgetRef ref, { required Function() onPressed, bool isSignInButton = false, }) { final localizations = ref.text; const googleBlue = Color(0xff4285F4); const googleText = Color(0x89000000); return Theme( data: ThemeData( brightness: Brightness.light, colorScheme: ColorScheme.fromSwatch().copyWith(secondary: googleBlue), ), child: PlatformTextButton( onPressed: onPressed, child: Container( decoration: BoxDecoration( border: Border.all(color: googleBlue), color: Colors.white, ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Image.asset( 'assets/images/providers/$key.png', height: 50, fit: BoxFit.contain, errorBuilder: (context, error, stacktrace) => Container(), package: 'enough_mail_app', ), Padding( padding: const EdgeInsets.only(left: 8, right: 16), child: Text( localizations.addAccountOauthSignInGoogle, style: GoogleFonts.roboto( color: googleText, fontWeight: FontWeight.w500, ), ), ), ], ), ), ), ); } } class OutlookMailHoster extends MailHoster { OutlookMailHoster() : super( 'outlook', 'outlook.office365.com', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'Outlook.com', displayShortName: 'Outlook', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'outlook.office365.com', port: 993, socketType: SocketType.ssl, authentication: Authentication.oauth2, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'smtp.office365.com', port: 587, socketType: SocketType.starttls, authentication: Authentication.oauth2, usernameType: UsernameType.emailAddress, ), ], ), ], oauthClient: OutlookOAuthClient(), appSpecificPasswordSetupUrl: 'https://support.microsoft.com/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944', domains: [ 'hotmail.com', 'live.com', 'msn.com', 'windowslive.com', 'outlook.at', 'outlook.be', 'outlook.cl', 'outlook.cz', 'outlook.de', 'outlook.dk', 'outlook.es', 'outlook.fr', 'outlook.hu', 'outlook.ie', 'outlook.in', 'outlook.it', 'outlook.jp', 'outlook.kr', 'outlook.lv', 'outlook.my', 'outlook.ph', 'outlook.pt', 'outlook.sa', 'outlook.sg', 'outlook.sk', 'outlook.co.id', 'outlook.co.il', 'outlook.co.th', 'outlook.com.ar', 'outlook.com.au', 'outlook.com.br', 'outlook.com.gr', 'outlook.com.tr', 'outlook.com.vn', 'hotmail.be', 'hotmail.ca', 'hotmail.cl', 'hotmail.cz', 'hotmail.de', 'hotmail.dk', 'hotmail.es', 'hotmail.fi', 'hotmail.fr', 'hotmail.gr', 'hotmail.hu', 'hotmail.it', 'hotmail.lt', 'hotmail.lv', 'hotmail.my', 'hotmail.nl', 'hotmail.no', 'hotmail.ph', 'hotmail.rs', 'hotmail.se', 'hotmail.sg', 'hotmail.sk', 'hotmail.co.id', 'hotmail.co.il', 'hotmail.co.in', 'hotmail.co.jp', 'hotmail.co.kr', 'hotmail.co.th', 'hotmail.co.uk', 'hotmail.co.za', 'hotmail.com.ar', 'hotmail.com.au', 'hotmail.com.br', 'hotmail.com.hk', 'hotmail.com.tr', 'hotmail.com.tw', 'hotmail.com.vn', 'live.at', 'live.be', 'live.ca', 'live.cl', 'live.cn', 'live.de', 'live.dk', 'live.fi', 'live.fr', 'live.hk', 'live.ie', 'live.in', 'live.it', 'live.jp', 'live.nl', 'live.no', 'live.ru', 'live.se', 'live.co.jp', 'live.co.kr', 'live.co.uk', 'live.co.za', 'live.com.ar', 'live.com.au', 'live.com.mx', 'live.com.my', 'live.com.ph', 'live.com.pt', 'live.com.sg', 'livemail.tw', 'olc.protection.outlook.com', ], ); } class YahooMailHoster extends MailHoster { YahooMailHoster() : super( 'yahoo', 'imap.mail.yahoo.com', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'Yahoo! Mail', displayShortName: 'Yahoo', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'imap.mail.yahoo.com', port: 993, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'smtp.mail.yahoo.com', port: 465, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], ), ], appSpecificPasswordSetupUrl: 'https://help.yahoo.com/kb/SLN15241.html', domains: [ 'yahoo.com', 'yahoo.de', 'yahoo.it', 'yahoo.fr', 'yahoo.es', 'yahoo.se', 'yahoo.co.uk', 'yahoo.co.nz', 'yahoo.com.au', 'yahoo.com.ar', 'yahoo.com.br', 'yahoo.com.mx', 'ymail.com', 'rocketmail.com', 'mail.am0.yahoodns.net', 'am0.yahoodns.net', 'yahoodns.net', ], ); } class AolMailHoster extends MailHoster { AolMailHoster() : super( 'aol', 'imap.aol.com', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'AOL Mail', displayShortName: 'AOL', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'imap.aol.com', port: 993, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'smtp.aol.com', port: 465, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], ), ], appSpecificPasswordSetupUrl: 'https://help.aol.com/articles/Create-and-manage-app-password', domains: [ 'aol.com', 'aim.com', 'netscape.net', 'netscape.com', 'compuserve.com', 'cs.com', 'wmconnect.com', 'aol.de', 'aol.it', 'aol.fr', 'aol.es', 'aol.se', 'aol.co.uk', 'aol.co.nz', 'aol.com.au', 'aol.com.ar', 'aol.com.br', 'aol.com.mx', 'mail.gm0.yahoodns.net', ], ); } class AppleMailHoster extends MailHoster { AppleMailHoster() : super( 'apple', 'imap.mail.me.com', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'Apple iCloud', displayShortName: 'Apple', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'imap.mail.me.com', port: 993, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'smtp.mail.me.com', port: 587, socketType: SocketType.starttls, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], ), ], appSpecificPasswordSetupUrl: 'https://support.apple.com/en-us/HT204397', domains: ['mac.com', 'me.com', 'icloud.com'], ); } class GmxMailHoster extends MailHoster { GmxMailHoster() : super( 'gmx', 'imap.gmx.net', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'GMX Freemail', displayShortName: 'GMX', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'imap.gmx.net', port: 993, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'mail.gmx.net', port: 465, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], ), ], manualImapAccessSetupUrl: 'https://hilfe.gmx.net/pop-imap/einschalten.html', domains: [ 'gmx.net', 'gmx.de', 'gmx.at', 'gmx.ch', 'gmx.eu', 'gmx.biz', 'gmx.org', 'gmx.info', ], ); } class MailboxOrMailHoster extends MailHoster { MailboxOrMailHoster() : super( 'mailbox_org', 'imap.gmx.net', ClientConfig() ..emailProviders = [ ConfigEmailProvider( displayName: 'mailbox.org', displayShortName: 'mailbox', incomingServers: [ const ServerConfig( type: ServerType.imap, hostname: 'imap.mailbox.org', port: 993, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], outgoingServers: [ const ServerConfig( type: ServerType.smtp, hostname: 'smtp.mailbox.org', port: 465, socketType: SocketType.ssl, authentication: Authentication.passwordClearText, usernameType: UsernameType.emailAddress, ), ], ), ], domains: ['mailbox.org'], ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/keys/service.dart
// ignore_for_file: do_not_use_environment import '../oauth/oauth.dart'; /// Allows to load the keys from assets/keys.txt class KeyService { /// Creates a new [KeyService] KeyService._(); static final _instance = KeyService._(); /// Retrieves access to the [KeyService] singleton static KeyService get instance => _instance; /// Loads the key data Future<void> init() async { void addOauth(String key, String value) { if (value.isEmpty) { return; } final valueIndex = value.indexOf(':'); if (valueIndex == -1) { oauth[key] = OauthClientId(value, null); } else { oauth[key] = OauthClientId( value.substring(0, valueIndex), value.substring(valueIndex + 1), ); } } const giphyApiKey = String.fromEnvironment('GIPHY_API_KEY'); _giphy = giphyApiKey.isEmpty ? null : giphyApiKey; addOauth( 'imap.gmail.com', const String.fromEnvironment('OAUTH_GMAIL'), ); addOauth( 'outlook.office365.com', const String.fromEnvironment('OAUTH_OUTLOOK'), ); } String? _giphy; /// The giphy API key String? get giphy => _giphy; /// Whether the giphy API key is available bool get hasGiphy => _giphy != null; /// The oauth client ids final oauth = <String, OauthClientId>{}; /// Whether the oauth client id is available for the given [incomingHostname] bool hasOauthFor(String incomingHostname) => oauth[incomingHostname] != null; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/settings/storage.dart
import 'dart:convert'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import '../logger.dart'; import 'model.dart'; /// Allows to read and store settings class SettingsStorage { /// Creates a [SettingsStorage] const SettingsStorage({ FlutterSecureStorage storage = const FlutterSecureStorage(), }) : _storage = storage; static const String _keySettings = 'settings'; final FlutterSecureStorage _storage; /// Loads the settings Future<Settings> load() async { final json = await _storage.read(key: _keySettings); if (json != null) { try { return Settings.fromJson(jsonDecode(json)); } catch (e) { logger.d('error loading settings: $e'); } } return const Settings(); } /// Saves the given settings Future<void> save(Settings value) => _storage.write( key: _keySettings, value: jsonEncode(value.toJson()), ); }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/settings/model.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'model.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Settings _$SettingsFromJson(Map<String, dynamic> json) => Settings( blockExternalImages: json['blockExternalImages'] as bool? ?? false, preferredComposeMailAddress: json['preferredComposeMailAddress'] as String?, languageTag: json['languageTag'] as String?, themeSettings: json['themeSettings'] == null ? const ThemeSettings() : ThemeSettings.fromJson( json['themeSettings'] as Map<String, dynamic>), swipeLeftToRightAction: $enumDecodeNullable( _$SwipeActionEnumMap, json['swipeLeftToRightAction']) ?? SwipeAction.markRead, swipeRightToLeftAction: $enumDecodeNullable( _$SwipeActionEnumMap, json['swipeRightToLeftAction']) ?? SwipeAction.delete, folderNameSetting: $enumDecodeNullable( _$FolderNameSettingEnumMap, json['folderNameSetting']) ?? FolderNameSetting.localized, customFolderNames: (json['customFolderNames'] as List<dynamic>?) ?.map((e) => e as String) .toList(), enableDeveloperMode: json['enableDeveloperMode'] as bool? ?? false, signatureHtml: json['signatureHtml'] as String?, signaturePlain: json['signaturePlain'] as String?, signatureActions: (json['signatureActions'] as List<dynamic>?) ?.map((e) => $enumDecode(_$ComposeActionEnumMap, e)) .toList() ?? const [ComposeAction.newMessage], readReceiptDisplaySetting: $enumDecodeNullable( _$ReadReceiptDisplaySettingEnumMap, json['readReceiptDisplaySetting']) ?? ReadReceiptDisplaySetting.always, defaultSender: json['defaultSender'] == null ? null : MailAddress.fromJson(json['defaultSender'] as Map<String, dynamic>), preferPlainTextMessages: json['preferPlainTextMessages'] as bool? ?? false, urlLaunchMode: $enumDecodeNullable(_$LaunchModeEnumMap, json['urlLaunchMode']) ?? LaunchMode.externalApplication, replyFormatPreference: $enumDecodeNullable( _$ReplyFormatPreferenceEnumMap, json['replyFormatPreference']) ?? ReplyFormatPreference.alwaysHtml, enableBiometricLock: json['enableBiometricLock'] as bool? ?? false, lockTimePreference: $enumDecodeNullable( _$LockTimePreferenceEnumMap, json['enableBiometricLockTime']) ?? LockTimePreference.immediately, ); Map<String, dynamic> _$SettingsToJson(Settings instance) => <String, dynamic>{ 'blockExternalImages': instance.blockExternalImages, 'preferredComposeMailAddress': instance.preferredComposeMailAddress, 'languageTag': instance.languageTag, 'themeSettings': instance.themeSettings, 'swipeLeftToRightAction': _$SwipeActionEnumMap[instance.swipeLeftToRightAction]!, 'swipeRightToLeftAction': _$SwipeActionEnumMap[instance.swipeRightToLeftAction]!, 'folderNameSetting': _$FolderNameSettingEnumMap[instance.folderNameSetting]!, 'customFolderNames': instance.customFolderNames, 'enableDeveloperMode': instance.enableDeveloperMode, 'signatureHtml': instance.signatureHtml, 'signaturePlain': instance.signaturePlain, 'signatureActions': instance.signatureActions .map((e) => _$ComposeActionEnumMap[e]!) .toList(), 'readReceiptDisplaySetting': _$ReadReceiptDisplaySettingEnumMap[ instance.readReceiptDisplaySetting]!, 'defaultSender': instance.defaultSender, 'preferPlainTextMessages': instance.preferPlainTextMessages, 'urlLaunchMode': _$LaunchModeEnumMap[instance.urlLaunchMode]!, 'replyFormatPreference': _$ReplyFormatPreferenceEnumMap[instance.replyFormatPreference]!, 'enableBiometricLock': instance.enableBiometricLock, 'enableBiometricLockTime': _$LockTimePreferenceEnumMap[instance.lockTimePreference]!, }; const _$SwipeActionEnumMap = { SwipeAction.markRead: 'markRead', SwipeAction.archive: 'archive', SwipeAction.markJunk: 'markJunk', SwipeAction.delete: 'delete', SwipeAction.flag: 'flag', }; const _$FolderNameSettingEnumMap = { FolderNameSetting.server: 'server', FolderNameSetting.localized: 'localized', FolderNameSetting.custom: 'custom', }; const _$ComposeActionEnumMap = { ComposeAction.answer: 'answer', ComposeAction.forward: 'forward', ComposeAction.newMessage: 'newMessage', }; const _$ReadReceiptDisplaySettingEnumMap = { ReadReceiptDisplaySetting.always: 'always', ReadReceiptDisplaySetting.never: 'never', }; const _$LaunchModeEnumMap = { LaunchMode.platformDefault: 'platformDefault', LaunchMode.inAppWebView: 'inAppWebView', LaunchMode.inAppBrowserView: 'inAppBrowserView', LaunchMode.externalApplication: 'externalApplication', LaunchMode.externalNonBrowserApplication: 'externalNonBrowserApplication', }; const _$ReplyFormatPreferenceEnumMap = { ReplyFormatPreference.alwaysHtml: 'alwaysHtml', ReplyFormatPreference.sameFormat: 'sameFormat', ReplyFormatPreference.alwaysPlainText: 'alwaysPlainText', }; const _$LockTimePreferenceEnumMap = { LockTimePreference.immediately: 'immediately', LockTimePreference.after5minutes: 'after5minutes', LockTimePreference.after30minutes: 'after30minutes', };
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/settings/settings.dart
export 'home/home.dart'; export 'model.dart'; export 'provider.dart';
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/settings/provider.dart
import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../account/model.dart'; import '../localization/extension.dart'; import '../logger.dart'; import '../models/compose_data.dart'; import 'model.dart'; import 'storage.dart'; /// Provides the settings final settingsProvider = NotifierProvider<SettingsNotifier, Settings>(SettingsNotifier.new); /// Provides the settings class SettingsNotifier extends Notifier<Settings> { /// Creates a [SettingsNotifier] SettingsNotifier({ Settings settings = const Settings(), SettingsStorage storage = const SettingsStorage(), }) : _initialSettings = settings, _storage = storage; final Settings _initialSettings; final SettingsStorage _storage; @override Settings build() => _initialSettings; /// Initializes the settings notifier Future<void> init() async { try { final settings = await _storage.load(); state = settings; } catch (e) { logger.e('Unable to load settings: $e'); } } /// Updates and saves the given [value] settings Future<void> update(Settings value) async { state = value; try { await _storage.save(value); } catch (e) { logger.e('Unable to save settings: $e'); } } /// Retrieves the HTML signature for the specified [account] /// and [composeAction] String getSignatureHtml( RealAccount account, ComposeAction composeAction, String? languageCode, ) { if (!state.signatureActions.contains(composeAction)) { return ''; } return account.getSignatureHtml(languageCode) ?? getSignatureHtmlGlobal(); } /// Retrieves the global signature String getSignatureHtmlGlobal() => state.signatureHtml ?? '<p>---<br/>${ref.text.signature}</p>'; /// Retrieves the plain text signature for the specified account String getSignaturePlain( RealAccount account, ComposeAction composeAction, ) { if (!state.signatureActions.contains(composeAction)) { return ''; } return account.signaturePlain ?? getSignaturePlainGlobal(); } /// Retrieves the global plain text signature String getSignaturePlainGlobal() => state.signaturePlain ?? '\n---\n${ref.text.signature}'; }
0
mirrored_repositories/enough_mail_app/lib/src
mirrored_repositories/enough_mail_app/lib/src/settings/model.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:url_launcher/url_launcher.dart'; import '../models/compose_data.dart'; import '../models/swipe.dart'; import 'theme/model.dart'; part 'model.g.dart'; /// The shown name for folders enum FolderNameSetting { /// Show the name as defined by the server server, /// Show localized names localized, /// Show the names as defined by the user custom, } /// The display setting for read receipts enum ReadReceiptDisplaySetting { /// Always show read receipt requests always, /// Never show read receipt requests never, // forContacts, } /// The format preference for replies enum ReplyFormatPreference { /// Always reply in HTML format alwaysHtml, /// Reply in the same format as the original message sameFormat, /// Always reply in plain text format alwaysPlainText, } /// The app lock time preference enum LockTimePreference { /// Lock the app immediately when bringing it to the background immediately, /// Lock the app after 5 minutes after5minutes, /// Lock the app after 30 minutes after30minutes, } /// Provides more information about [LockTimePreference] extension ExtensionLockTimePreference on LockTimePreference { /// Returns true if the app requires authorization bool requiresAuthorization(DateTime? lastPausedTimeStamp) => lastPausedTimeStamp == null || lastPausedTimeStamp.isBefore(DateTime.now().subtract(duration)); /// Returns the duration for this lock time preference Duration get duration { switch (this) { case LockTimePreference.immediately: return Duration.zero; case LockTimePreference.after5minutes: return const Duration(minutes: 5); case LockTimePreference.after30minutes: return const Duration(minutes: 30); } } } /// Contains the settings of the app @JsonSerializable() class Settings { /// Creates new settings const Settings({ this.blockExternalImages = false, this.preferredComposeMailAddress, this.languageTag, this.themeSettings = const ThemeSettings(), this.swipeLeftToRightAction = SwipeAction.markRead, this.swipeRightToLeftAction = SwipeAction.delete, this.folderNameSetting = FolderNameSetting.localized, this.customFolderNames, this.enableDeveloperMode = false, this.signatureHtml, this.signaturePlain, this.signatureActions = const [ComposeAction.newMessage], this.readReceiptDisplaySetting = ReadReceiptDisplaySetting.always, this.defaultSender, this.preferPlainTextMessages = false, this.urlLaunchMode = LaunchMode.externalApplication, this.replyFormatPreference = ReplyFormatPreference.alwaysHtml, this.enableBiometricLock = false, this.lockTimePreference = LockTimePreference.immediately, }); /// Creates settings from the given [json] factory Settings.fromJson(Map<String, dynamic> json) => _$SettingsFromJson(json); /// Converts these settings to JSON Map<String, dynamic> toJson() => _$SettingsToJson(this); /// Should external images being blocked? final bool blockExternalImages; /// The preferred email address for sending new messages final String? preferredComposeMailAddress; /// The language of the app final String? languageTag; /// The theme settings final ThemeSettings themeSettings; /// The action for swiping from left to right final SwipeAction swipeLeftToRightAction; /// The action for swiping from right to left final SwipeAction swipeRightToLeftAction; /// The folder name setting final FolderNameSetting folderNameSetting; /// The custom folder names final List<String>? customFolderNames; /// Should the developer mode of the app be active? final bool enableDeveloperMode; /// The default, global HTML signature final String? signatureHtml; /// The default, global plain text signature final String? signaturePlain; /// The signature actions final List<ComposeAction> signatureActions; /// Should read receipt requests been shown? final ReadReceiptDisplaySetting readReceiptDisplaySetting; /// The default sender final MailAddress? defaultSender; /// Should messages been shown in plain text when possible? final bool preferPlainTextMessages; /// The launch mode for links - either "in app" or "external" final LaunchMode urlLaunchMode; /// The default reply format final ReplyFormatPreference replyFormatPreference; /// Should the app be locked with biometric authentication? final bool enableBiometricLock; /// The lock time preference @JsonKey(name: 'enableBiometricLockTime') final LockTimePreference lockTimePreference; /// Copies this settings with the given values Settings copyWith({ bool? blockExternalImages, String? preferredComposeMailAddress, String? languageTag, ThemeSettings? themeSettings, SwipeAction? swipeLeftToRightAction, SwipeAction? swipeRightToLeftAction, FolderNameSetting? folderNameSetting, List<String>? customFolderNames, bool? enableDeveloperMode, String? signatureHtml, String? signaturePlain, List<ComposeAction>? signatureActions, ReadReceiptDisplaySetting? readReceiptDisplaySetting, MailAddress? defaultSender, bool? preferPlainTextMessages, LaunchMode? urlLaunchMode, ReplyFormatPreference? replyFormatPreference, bool? enableBiometricLock, LockTimePreference? lockTimePreference, }) => Settings( blockExternalImages: blockExternalImages ?? this.blockExternalImages, preferredComposeMailAddress: preferredComposeMailAddress ?? this.preferredComposeMailAddress, languageTag: languageTag ?? this.languageTag, themeSettings: themeSettings ?? this.themeSettings, swipeLeftToRightAction: swipeLeftToRightAction ?? this.swipeLeftToRightAction, swipeRightToLeftAction: swipeRightToLeftAction ?? this.swipeRightToLeftAction, folderNameSetting: folderNameSetting ?? this.folderNameSetting, customFolderNames: customFolderNames ?? this.customFolderNames, enableDeveloperMode: enableDeveloperMode ?? this.enableDeveloperMode, signatureHtml: signatureHtml ?? this.signatureHtml, signaturePlain: signaturePlain ?? this.signaturePlain, signatureActions: signatureActions ?? this.signatureActions, readReceiptDisplaySetting: readReceiptDisplaySetting ?? this.readReceiptDisplaySetting, defaultSender: defaultSender ?? this.defaultSender, preferPlainTextMessages: preferPlainTextMessages ?? this.preferPlainTextMessages, urlLaunchMode: urlLaunchMode ?? this.urlLaunchMode, replyFormatPreference: replyFormatPreference ?? this.replyFormatPreference, enableBiometricLock: enableBiometricLock ?? this.enableBiometricLock, lockTimePreference: lockTimePreference ?? this.lockTimePreference, ); /// Copies the settings without the signatures Settings withoutSignatures() => Settings( blockExternalImages: blockExternalImages, customFolderNames: customFolderNames, defaultSender: defaultSender, enableBiometricLock: enableBiometricLock, enableDeveloperMode: enableDeveloperMode, folderNameSetting: folderNameSetting, languageTag: languageTag, lockTimePreference: lockTimePreference, preferPlainTextMessages: preferPlainTextMessages, preferredComposeMailAddress: preferredComposeMailAddress, readReceiptDisplaySetting: readReceiptDisplaySetting, replyFormatPreference: replyFormatPreference, signatureActions: signatureActions, swipeLeftToRightAction: swipeLeftToRightAction, swipeRightToLeftAction: swipeRightToLeftAction, themeSettings: themeSettings, urlLaunchMode: urlLaunchMode, ); Settings removeLanguageTag() => Settings( blockExternalImages: blockExternalImages, customFolderNames: customFolderNames, defaultSender: defaultSender, enableBiometricLock: enableBiometricLock, enableDeveloperMode: enableDeveloperMode, folderNameSetting: folderNameSetting, lockTimePreference: lockTimePreference, preferPlainTextMessages: preferPlainTextMessages, preferredComposeMailAddress: preferredComposeMailAddress, readReceiptDisplaySetting: readReceiptDisplaySetting, replyFormatPreference: replyFormatPreference, signatureActions: signatureActions, signatureHtml: signatureHtml, signaturePlain: signaturePlain, swipeLeftToRightAction: swipeLeftToRightAction, swipeRightToLeftAction: swipeRightToLeftAction, themeSettings: themeSettings, urlLaunchMode: urlLaunchMode, ); }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_folders_screen.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../account/model.dart'; import '../../account/provider.dart'; import '../../localization/extension.dart'; import '../../mail/provider.dart'; import '../../models/models.dart'; import '../../scaffold_messenger/service.dart'; import '../../screens/base.dart'; import '../../util/localized_dialog_helper.dart'; import '../../widgets/account_selector.dart'; import '../../widgets/mailbox_selector.dart'; import '../model.dart'; import '../provider.dart'; import '../theme/icon_service.dart'; class SettingsFoldersScreen extends ConsumerWidget { const SettingsFoldersScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final localizations = ref.text; final settings = ref.watch(settingsProvider); final folderNameSetting = settings.folderNameSetting; void onFolderNameSettingChanged(FolderNameSetting? value) => _onFolderNameSettingChanged(context, value, ref); return BasePage( title: localizations.settingsFolders, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.folderNamesIntroduction, style: theme.textTheme.bodySmall, ), PlatformRadioListTile<FolderNameSetting>( value: FolderNameSetting.localized, groupValue: folderNameSetting, onChanged: onFolderNameSettingChanged, title: Text(localizations.folderNamesSettingLocalized), ), PlatformRadioListTile<FolderNameSetting>( value: FolderNameSetting.server, groupValue: folderNameSetting, onChanged: onFolderNameSettingChanged, title: Text(localizations.folderNamesSettingServer), ), PlatformRadioListTile<FolderNameSetting>( value: FolderNameSetting.custom, groupValue: folderNameSetting, onChanged: onFolderNameSettingChanged, title: Text(localizations.folderNamesSettingCustom), ), if (folderNameSetting == FolderNameSetting.custom) ...[ const Divider(), PlatformTextButtonIcon( icon: Icon(CommonPlatformIcons.edit), label: Text(localizations.folderNamesEditAction), onPressed: () => _editFolderNames(context, settings, ref), ), ], const Divider( height: 8, ), const FolderManagement(), ], ), ), ), ), ); } Future<void> _editFolderNames( BuildContext context, Settings settings, WidgetRef ref, ) async { final localizations = ref.text; var customNames = settings.customFolderNames; if (customNames == null) { final l = ref.text; customNames = [ l.folderInbox, l.folderDrafts, l.folderSent, l.folderTrash, l.folderArchive, l.folderJunk, ]; } final result = await LocalizedDialogHelper.showWidgetDialog( ref, CustomFolderNamesEditor(customNames: customNames), title: localizations.folderNamesCustomTitle, defaultActions: DialogActions.okAndCancel, ); if (result == true) { await ref.read(settingsProvider.notifier).update( settings.copyWith(customFolderNames: customNames), ); } } Future<void> _onFolderNameSettingChanged( BuildContext context, FolderNameSetting? value, WidgetRef ref, ) async { final settings = ref.read(settingsProvider); await ref.read(settingsProvider.notifier).update( settings.copyWith(folderNameSetting: value), ); } } class CustomFolderNamesEditor extends HookConsumerWidget { const CustomFolderNamesEditor({super.key, required this.customNames}); final List<String> customNames; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final iconService = IconService.instance; final inboxController = useTextEditingController(text: customNames[0]); final draftsController = useTextEditingController(text: customNames[1]); final sentController = useTextEditingController(text: customNames[2]); final trashController = useTextEditingController(text: customNames[3]); final archiveController = useTextEditingController(text: customNames[4]); final junkController = useTextEditingController(text: customNames[5]); // TODO(RV): support to save these values return SingleChildScrollView( child: SafeArea( child: Column( children: [ DecoratedPlatformTextField( controller: inboxController, decoration: InputDecoration( labelText: localizations.folderInbox, prefixIcon: Icon(iconService.folderInbox), ), onChanged: (value) => customNames[0] = value, cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: draftsController, decoration: InputDecoration( labelText: localizations.folderDrafts, prefixIcon: Icon(iconService.folderDrafts), ), onChanged: (value) => customNames[1] = value, cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: sentController, decoration: InputDecoration( labelText: localizations.folderSent, prefixIcon: Icon(iconService.folderSent), ), onChanged: (value) => customNames[2] = value, cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: trashController, decoration: InputDecoration( labelText: localizations.folderTrash, prefixIcon: Icon(iconService.folderTrash), ), onChanged: (value) => customNames[3] = value, cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: archiveController, decoration: InputDecoration( labelText: localizations.folderArchive, prefixIcon: Icon(iconService.folderArchive), ), onChanged: (value) => customNames[4] = value, cupertinoAlignLabelOnTop: true, ), DecoratedPlatformTextField( controller: junkController, decoration: InputDecoration( labelText: localizations.folderJunk, prefixIcon: Icon(iconService.folderJunk), ), onChanged: (value) => customNames[5] = value, cupertinoAlignLabelOnTop: true, ), ], ), ), ); } } class FolderManagement extends StatefulHookConsumerWidget { const FolderManagement({super.key}); @override ConsumerState<FolderManagement> createState() => _FolderManagementState(); } class _FolderManagementState extends ConsumerState<FolderManagement> { late RealAccount _account; Mailbox? _mailbox; late TextEditingController _folderNameController; @override void initState() { final account = ref.read(currentAccountProvider); _account = account is RealAccount ? account : ref.read(realAccountsProvider).first; _folderNameController = TextEditingController(); super.initState(); } @override void dispose() { _folderNameController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final localizations = ref.text; return SingleChildScrollView( child: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(localizations.folderAccountLabel), AccountSelector( account: _account, onChanged: (account) { setState(() { _mailbox = null; _account = account; }); }, ), const Divider(), Text(localizations.folderMailboxLabel), MailboxSelector( account: _account, mailbox: _mailbox, onChanged: (mailbox) { setState(() { _mailbox = mailbox; }); }, ), const Divider(), MailboxWidget( mailbox: _mailbox, account: _account, onMailboxAdded: () { setState(() {}); }, onMailboxDeleted: () { setState(() { _mailbox = null; }); }, ), ], ), ), ); } } class MailboxWidget extends ConsumerWidget { const MailboxWidget({ super.key, required this.mailbox, required this.account, required this.onMailboxAdded, required this.onMailboxDeleted, }); final RealAccount account; final Mailbox? mailbox; final void Function() onMailboxAdded; final void Function() onMailboxDeleted; @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ PlatformTextButtonIcon( onPressed: () => _createFolder(context, ref), icon: Icon(CommonPlatformIcons.add), label: Text(localizations.folderAddAction), ), if (mailbox != null) PlatformTextButtonIcon( onPressed: () => _deleteFolder(context, ref), backgroundColor: Colors.red, style: TextButton.styleFrom(backgroundColor: Colors.red), icon: Icon( CommonPlatformIcons.delete, color: Colors.white, ), label: Text( localizations.folderDeleteAction, style: Theme.of(context).textTheme.labelLarge?.copyWith( color: Colors.white, ), ), ), ], ); } Future<void> _createFolder(BuildContext context, WidgetRef ref) async { final localizations = ref.text; final folderNameController = TextEditingController(); final result = await LocalizedDialogHelper.showWidgetDialog( ref, DecoratedPlatformTextField( controller: folderNameController, decoration: InputDecoration( labelText: localizations.folderAddNameLabel, hintText: localizations.folderAddNameHint, ), textInputAction: TextInputAction.done, ), title: localizations.folderAddTitle, defaultActions: DialogActions.okAndCancel, ); if (result == true) { try { await ref .read(mailClientSourceProvider(account: account).notifier) .createMailbox( folderNameController.text, mailbox, ); ScaffoldMessengerService.instance.showTextSnackBar( localizations, localizations.folderAddResultSuccess, ); onMailboxAdded(); } on MailException catch (e) { if (context.mounted) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.folderAddResultFailure(e.message ?? e.toString()), ); } } } } Future<void> _deleteFolder(BuildContext context, WidgetRef ref) async { final localizations = ref.text; final mailbox = this.mailbox; if (mailbox == null) { return; } final confirmed = await LocalizedDialogHelper.askForConfirmation( ref, title: localizations.folderDeleteConfirmTitle, query: localizations.folderDeleteConfirmText(mailbox.path), ); if (confirmed ?? false) { try { await ref .read(mailClientSourceProvider(account: account).notifier) .deleteMailbox(mailbox); ScaffoldMessengerService.instance.showTextSnackBar( localizations, localizations.folderDeleteResultSuccess, ); onMailboxDeleted(); } on MailException catch (e) { if (context.mounted) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.folderDeleteResultFailure(e.message ?? e.toString()), ); } } } } }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_accounts_screen.dart
import 'dart:async'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../account/model.dart'; import '../../account/provider.dart'; import '../../localization/app_localizations.g.dart'; import '../../localization/extension.dart'; import '../../routes/routes.dart'; import '../../screens/base.dart'; /// Allows to select an account for editing and to re-order the accounts class SettingsAccountsScreen extends HookConsumerWidget { /// Creates a [SettingsAccountsScreen] const SettingsAccountsScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final reorderAccountsState = useState(false); final accounts = ref.watch(realAccountsProvider); final localizations = ref.text; return BasePage( title: localizations.accountsTitle, content: reorderAccountsState.value ? _buildReorderableListView( context, localizations, ref, reorderAccountsState, accounts, ) : _buildAccountSettings( context, localizations, ref, reorderAccountsState, accounts, ), ); } Widget _buildAccountSettings( BuildContext context, AppLocalizations localizations, WidgetRef ref, ValueNotifier<bool> reorderAccountsState, List<RealAccount> accounts, ) => SingleChildScrollView( child: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ for (final account in accounts) PlatformListTile( leading: account.hasError ? Badge(child: Icon(CommonPlatformIcons.account)) : Icon(CommonPlatformIcons.account), title: Text(account.name), onTap: () => context.pushNamed( Routes.accountEdit, pathParameters: {Routes.pathParameterEmail: account.email}, ), ), PlatformListTile( leading: Icon(CommonPlatformIcons.add), title: Text(localizations.drawerEntryAddAccount), onTap: () => context.pushNamed(Routes.accountAdd), ), if (accounts.length > 1) Padding( padding: const EdgeInsets.all(8), child: PlatformElevatedButton( onPressed: () => reorderAccountsState.value = true, child: Text(localizations.accountsActionReorder), ), ), ], ), ), ); Widget _buildReorderableListView( BuildContext context, AppLocalizations localizations, WidgetRef ref, ValueNotifier<bool> reorderAccountsState, List<RealAccount> accounts, ) => WillPopScope( onWillPop: () { reorderAccountsState.value = false; return Future.value(false); }, child: SafeArea( child: Material( child: ReorderableListView( onReorder: (oldIndex, newIndex) async { // print('moved $oldIndex to $newIndex'); final account = accounts.removeAt(oldIndex); if (newIndex > accounts.length) { accounts.add(account); } else { accounts.insert(newIndex, account); } ref .read(realAccountsProvider.notifier) .reorderAccounts(accounts); }, children: [ for (final account in accounts) ListTile( key: ValueKey(account), leading: const Icon(Icons.account_circle), title: Text(account.name), ), ], ), ), ), ); }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_language_screen.dart
import 'package:collection/collection.dart' show IterableExtension; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../localization/app_localizations.g.dart'; import '../../localization/extension.dart'; import '../../screens/base.dart'; import '../../util/localized_dialog_helper.dart'; import '../provider.dart'; class SettingsLanguageScreen extends HookConsumerWidget { const SettingsLanguageScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final displayNames = { 'de': 'deutsch', 'en': 'English', 'es': 'español', }; final available = AppLocalizations.supportedLocales .map( (locale) => _Language(locale, displayNames[locale.toLanguageTag()]), ) .toList(); final systemLanguage = _Language( null, ref.text.designThemeOptionSystem, ); final languages = [systemLanguage, ...available]; final languageTag = ref.watch( settingsProvider.select((value) => value.languageTag), ); final _Language? selectedLanguage; selectedLanguage = languageTag != null ? available .firstWhereOrNull((l) => l.locale?.toLanguageTag() == languageTag) : systemLanguage; final theme = Theme.of(context); final localizations = ref.text; final systemSettingApplied = useState(false); final selectedLanguageState = useState(selectedLanguage); final selectedLocalizationsState = useState<AppLocalizations?>(null); return BasePage( title: localizations.languageSettingTitle, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.languageSettingLabel, style: theme.textTheme.bodySmall, ), PlatformDropdownButton<_Language>( value: selectedLanguage, onChanged: (value) async { final locale = value?.locale; final settings = ref.read(settingsProvider); if (locale == null) { systemSettingApplied.value = true; await ref .read(settingsProvider.notifier) .update(settings.removeLanguageTag()); return; } final selectedLocalizations = await AppLocalizations.delegate.load(locale); selectedLocalizationsState.value = selectedLocalizations; if (context.mounted) { final confirmed = await LocalizedDialogHelper.showTextDialog( ref, selectedLocalizations.languageSettingConfirmationTitle, selectedLocalizations.languageSettingConfirmationQuery, actions: [ PlatformTextButton( child: Text( selectedLocalizations.actionCancel, ), onPressed: () => context.pop(false), ), PlatformTextButton( child: Text(selectedLocalizations.actionOk), onPressed: () => context.pop(true), ), ], ); if (confirmed) { selectedLanguageState.value = value; await ref.read(settingsProvider.notifier).update( settings.copyWith( languageTag: locale.toLanguageTag(), ), ); } } }, selectedItemBuilder: (context) => languages .map((language) => Text(language.displayName ?? '')) .toList(), items: languages .map((language) => DropdownMenuItem( value: language, child: Text(language.displayName ?? ''), )) .toList(), ), if (selectedLocalizationsState.value != null) Text( selectedLocalizationsState.value?.languageSetInfo ?? '', style: theme.textTheme.titleMedium, ) else if (systemSettingApplied.value) Text( localizations.languageSystemSetInfo, style: theme.textTheme.titleMedium, ), ], ), ), ), ), ); } } class _Language { _Language(this.locale, this.displayName); final Locale? locale; final String? displayName; }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_signature_screen.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../account/model.dart'; import '../../account/provider.dart'; import '../../localization/extension.dart'; import '../../models/compose_data.dart'; import '../../routes/routes.dart'; import '../../screens/base.dart'; import '../../widgets/signature.dart'; import '../provider.dart'; class SettingsSignatureScreen extends HookConsumerWidget { const SettingsSignatureScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final signatureActions = ref.watch( settingsProvider.select( (value) => value.signatureActions, ), ); final signatureEnabledFor = useMemoized(() { final result = <ComposeAction, bool>{}; for (final action in ComposeAction.values) { result[action] = signatureActions.contains(action); } return result; }); final theme = Theme.of(context); final localizations = ref.text; final accounts = ref.read(realAccountsProvider); final accountsWithSignature = List<RealAccount>.from( accounts.where( (account) => account.getSignatureHtml(localizations.localeName) != null, ), ); String getActionName(ComposeAction action) { switch (action) { case ComposeAction.answer: return localizations.composeTitleReply; case ComposeAction.forward: return localizations.composeTitleForward; case ComposeAction.newMessage: return localizations.composeTitleNew; } } return BasePage( title: localizations.signatureSettingsTitle, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(localizations.signatureSettingsComposeActionsInfo), for (final action in ComposeAction.values) PlatformCheckboxListTile( value: signatureEnabledFor[action], onChanged: (value) { if (value != null) { // TODO(RV): check if this is actually updated signatureEnabledFor[action] = value; ref.read(settingsProvider.notifier).update( ref.read(settingsProvider).copyWith( signatureActions: value ? signatureActions + [action] : signatureActions .where((a) => a != action) .toList(), ), ); } }, title: Text(getActionName(action)), ), const Divider(), const SignatureWidget(), // global signature if (accounts.length > 1) ...[ const Divider(), if (accountsWithSignature.isNotEmpty) for (final account in accountsWithSignature) ...[ Text(account.name, style: theme.textTheme.titleMedium), SignatureWidget( account: account, ), const Divider(), ], Text(localizations.signatureSettingsAccountInfo), PlatformTextButton( onPressed: () { context.pushNamed(Routes.settingsAccounts); }, child: Text(localizations.settingsActionAccounts), ), ], ], ), ), ), ), ); } }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_reply_screen.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../localization/extension.dart'; import '../../screens/base.dart'; import '../model.dart'; import '../provider.dart'; class SettingsReplyScreen extends ConsumerWidget { const SettingsReplyScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; String getFormatPreferenceName(ReplyFormatPreference preference) { switch (preference) { case ReplyFormatPreference.alwaysHtml: return localizations.replySettingsFormatHtml; case ReplyFormatPreference.sameFormat: return localizations.replySettingsFormatSameAsOriginal; case ReplyFormatPreference.alwaysPlainText: return localizations.replySettingsFormatPlainText; } } final currentPreference = ref.watch( settingsProvider.select((value) => value.replyFormatPreference), ); return BasePage( title: localizations.replySettingsTitle, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(localizations.replySettingsIntro), for (final preference in ReplyFormatPreference.values) PlatformRadioListTile<ReplyFormatPreference>( value: preference, groupValue: currentPreference, onChanged: (value) async { if (value != null) { final settings = ref.read(settingsProvider); await ref.read(settingsProvider.notifier).update( settings.copyWith(replyFormatPreference: value), ); } }, title: Text( getFormatPreferenceName(preference), ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_default_sender_screen.dart
import 'package:enough_mail/enough_mail.dart'; import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../account/provider.dart'; import '../../localization/extension.dart'; import '../../routes/routes.dart'; import '../../screens/base.dart'; import '../../widgets/text_with_links.dart'; import '../provider.dart'; class SettingsDefaultSenderScreen extends ConsumerWidget { const SettingsDefaultSenderScreen({super.key}); // void initState() { // final senders = locator<MailService>() // .getSenders() // .map((sender) => sender.address) // .toList(); // _firstAccount = locator<I18nService>() // .localizations // .defaultSenderSettingsFirstAccount(senders.first.email); // _senders = [null, ...senders]; // _selectedSender = locator<SettingsService>().settings.defaultSender; // super.initState(); // } @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final localizations = ref.text; final defaultSender = ref.watch( settingsProvider.select( (value) => value.defaultSender, ), ); final availableSenders = ref.watch(sendersProvider).map((sender) => sender.address).toList(); final firstAccount = localizations .defaultSenderSettingsFirstAccount(availableSenders.first.email); final senders = [null, ...availableSenders]; final aliasInfo = localizations.defaultSenderSettingsAliasInfo; final accountSettings = localizations.defaultSenderSettingsAliasAccountSettings; final asIndex = aliasInfo.indexOf('[AS]'); final aliasInfoParts = [ TextLink(aliasInfo.substring(0, asIndex)), TextLink.callback( accountSettings, () => context.pushNamed(Routes.settingsAccounts), ), TextLink(aliasInfo.substring(asIndex + '[AS]'.length)), ]; return BasePage( title: localizations.defaultSenderSettingsTitle, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.defaultSenderSettingsLabel, style: theme.textTheme.bodySmall, ), FittedBox( child: PlatformDropdownButton<MailAddress>( value: defaultSender, onChanged: (value) async { final settings = ref.read(settingsProvider); await ref.read(settingsProvider.notifier).update( settings.copyWith(defaultSender: value), ); }, selectedItemBuilder: (context) => senders .map( (sender) => Text(sender?.toString() ?? firstAccount), ) .toList(), items: senders .map( (sender) => DropdownMenuItem( value: sender, child: Text(sender?.toString() ?? firstAccount), ), ) .toList(), ), ), Padding( padding: const EdgeInsets.only(top: 16), child: TextWithNamedLinks( parts: aliasInfoParts, ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/view.dart
export '../home/screen.dart'; export 'settings_accounts_screen.dart'; export 'settings_default_sender_screen.dart'; export 'settings_developer_mode_screen.dart'; export 'settings_feedback_screen.dart'; export 'settings_folders_screen.dart'; export 'settings_language_screen.dart'; export 'settings_readreceipts_screen.dart'; export 'settings_reply_screen.dart'; export 'settings_security_screen.dart'; export 'settings_signature_screen.dart'; export 'settings_swipe_screen.dart'; export 'settings_theme_screen.dart';
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_security_screen.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:url_launcher/url_launcher.dart' as launcher; import '../../app_lifecycle/provider.dart'; import '../../localization/extension.dart'; import '../../lock/provider.dart'; import '../../lock/service.dart'; import '../../screens/base.dart'; import '../../util/localized_dialog_helper.dart'; import '../model.dart'; import '../provider.dart'; class SettingsSecurityScreen extends HookConsumerWidget { const SettingsSecurityScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final settings = ref.watch(settingsProvider); final isBiometricsSupported = useState<bool?>(null); useMemoized(() async { final supported = await BiometricsService.instance.isDeviceSupported(); isBiometricsSupported.value = supported; }); String getLockTimePreferenceName(LockTimePreference preference) { switch (preference) { case LockTimePreference.immediately: return localizations.securityLockImmediately; case LockTimePreference.after5minutes: return localizations.securityLockAfter5Minutes; case LockTimePreference.after30minutes: return localizations.securityLockAfter30Minutes; } } return BasePage( title: localizations.securitySettingsTitle, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric( vertical: 8, horizontal: 4, ), child: Text( localizations.securitySettingsIntro, ), ), const Divider(), Row( children: [ Expanded( child: PlatformCheckboxListTile( value: settings.blockExternalImages, onChanged: (value) { ref.read(settingsProvider.notifier).update( settings.copyWith( blockExternalImages: value ?? false, ), ); }, title: Text( localizations.settingsSecurityBlockExternalImages, ), ), ), PlatformIconButton( icon: Icon(CommonPlatformIcons.info), onPressed: () => LocalizedDialogHelper.showTextDialog( ref, localizations .settingsSecurityBlockExternalImagesDescriptionTitle, localizations .settingsSecurityBlockExternalImagesDescriptionText, ), ), ], ), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: PlatformDropdownButton<bool>( value: settings.preferPlainTextMessages, onChanged: (value) { ref.read(settingsProvider.notifier).update( settings.copyWith( preferPlainTextMessages: value ?? false, ), ); }, items: [ DropdownMenuItem( value: false, child: Text( localizations.settingsSecurityMessageRenderingHtml, ), ), DropdownMenuItem( value: true, child: Text( localizations .settingsSecurityMessageRenderingPlainText, ), ), ], ), ), const Divider(), if (!(isBiometricsSupported.value ?? false)) Padding( padding: const EdgeInsets.all(8), child: Text(localizations.securityUnlockNotAvailable), ) else if (isBiometricsSupported.value ?? false) ...[ Row( children: [ Expanded( child: PlatformCheckboxListTile( value: settings.enableBiometricLock, onChanged: (value) async { final enableBiometricLock = value ?? false; final String? reason = enableBiometricLock ? null : localizations.securityUnlockDisableReason; ref .read(appLifecycleProvider.notifier) .ignoreNextInactivationCycle(); final didAuthenticate = await BiometricsService.instance.authenticate( localizations, reason: reason, ); if (didAuthenticate) { if (enableBiometricLock && context.mounted) { AppLock.ignoreNextSettingsChange = true; } await ref.read(settingsProvider.notifier).update( settings.copyWith( enableBiometricLock: enableBiometricLock, ), ); } }, title: Text( localizations.securityUnlockLabel, ), ), ), PlatformIconButton( icon: Icon(CommonPlatformIcons.info), onPressed: () => LocalizedDialogHelper.showTextDialog( ref, localizations.securityUnlockDescriptionTitle, localizations.securityUnlockDescriptionText, ), ), ], ), if (settings.enableBiometricLock) Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: PlatformDropdownButton<LockTimePreference>( value: settings.lockTimePreference, onChanged: (value) { ref.read(settingsProvider.notifier).update( settings.copyWith( lockTimePreference: value, ), ); }, items: LockTimePreference.values .map((preference) => DropdownMenuItem( value: preference, child: Text( getLockTimePreferenceName(preference), ), )) .toList(), ), ), ] else const Center( child: Padding( padding: EdgeInsets.all(8), child: CircularProgressIndicator(), ), ), const Divider(), Padding( padding: const EdgeInsets.fromLTRB(4, 8, 4, 4), child: Text(localizations.settingsSecurityLaunchModeLabel), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: PlatformDropdownButton<launcher.LaunchMode>( value: settings.urlLaunchMode, onChanged: (value) { if (value != null) { ref.read(settingsProvider.notifier).update( settings.copyWith( urlLaunchMode: value, ), ); } }, items: [ DropdownMenuItem( value: launcher.LaunchMode.externalApplication, child: Text( localizations.settingsSecurityLaunchModeExternal, ), ), DropdownMenuItem( value: launcher.LaunchMode.inAppWebView, child: Text(localizations.settingsSecurityLaunchModeInApp), ), ], ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_readreceipts_screen.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../localization/extension.dart'; import '../../screens/base.dart'; import '../model.dart'; import '../provider.dart'; class SettingsReadReceiptsScreen extends HookConsumerWidget { const SettingsReadReceiptsScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final readReceiptDisplaySetting = ref.watch( settingsProvider.select( (value) => value.readReceiptDisplaySetting, ), ); final theme = Theme.of(context); final localizations = ref.text; void onReadReceiptDisplaySettingChanged(ReadReceiptDisplaySetting? value) => _onReadReceiptDisplaySettingChanged(value, ref); return BasePage( title: localizations.settingsReadReceipts, content: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(8), child: SafeArea( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.readReceiptsSettingsIntroduction, style: theme.textTheme.bodySmall, ), PlatformRadioListTile<ReadReceiptDisplaySetting>( value: ReadReceiptDisplaySetting.always, groupValue: readReceiptDisplaySetting, onChanged: onReadReceiptDisplaySettingChanged, title: Text(localizations.readReceiptOptionAlways), ), PlatformRadioListTile<ReadReceiptDisplaySetting>( value: ReadReceiptDisplaySetting.never, groupValue: readReceiptDisplaySetting, onChanged: onReadReceiptDisplaySettingChanged, title: Text(localizations.readReceiptOptionNever), ), // PlatformRadioListTile<ReadReceiptDisplaySetting>( // value: ReadReceiptDisplaySetting.forContacts, // groupValue: readReceiptDisplaySetting, // onChanged: onReadReceiptDisplaySettingChanged, // title: Text(localizations.readReceiptOptionForContacts), // ), ], ), ), ), ), ); } Future<void> _onReadReceiptDisplaySettingChanged( ReadReceiptDisplaySetting? value, WidgetRef ref, ) async { if (value == null) return; final settings = ref.read(settingsProvider); await ref.read(settingsProvider.notifier).update( settings.copyWith(readReceiptDisplaySetting: value), ); } }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_developer_mode_screen.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:go_router/go_router.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:url_launcher/url_launcher.dart'; import '../../account/model.dart'; import '../../account/provider.dart'; import '../../extensions/extensions.dart'; import '../../localization/extension.dart'; import '../../screens/base.dart'; import '../../util/localized_dialog_helper.dart'; import '../provider.dart'; /// A screen to configure the developer mode. class SettingsDeveloperModeScreen extends HookConsumerWidget { /// Creates a new [SettingsDeveloperModeScreen]. const SettingsDeveloperModeScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); final localizations = ref.text; final isDeveloperModeEnabled = ref.watch( settingsProvider.select( (value) => value.enableDeveloperMode, ), ); final developerModeState = useState(isDeveloperModeEnabled); return BasePage( title: localizations.settingsDevelopment, content: SingleChildScrollView( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.developerModeTitle, style: theme.textTheme.titleMedium, ), Text( localizations.developerModeIntroduction, style: theme.textTheme.bodySmall, ), PlatformCheckboxListTile( value: isDeveloperModeEnabled, onChanged: (value) async { developerModeState.value = value ?? false; final settings = ref.read(settingsProvider); await ref.read(settingsProvider.notifier).update( settings.copyWith( enableDeveloperMode: value ?? false, ), ); }, title: Text(localizations.developerModeEnable), ), const Divider(), Text( localizations.extensionsTitle, style: theme.textTheme.titleMedium, ), Text( localizations.extensionsIntro, style: theme.textTheme.bodySmall, ), PlatformTextButton( child: Text(localizations.extensionsLearnMoreAction), onPressed: () => launchUrl( Uri.parse( 'https://github.com/Enough-Software/enough_mail_app/wiki/Extensions', ), ), ), PlatformListTile( title: Text(localizations.extensionsReloadAction), onTap: () => _reloadExtensions(context, ref), ), PlatformListTile( title: Text(localizations.extensionDeactivateAllAction), onTap: () => _deactivateAllExtensions(ref), ), PlatformListTile( title: Text(localizations.extensionsManualAction), onTap: () => _loadExtensionManually(context, ref), ), ], ), ), ), ), ); } Future<void> _loadExtensionManually( BuildContext context, WidgetRef ref, ) async { final localizations = ref.text; final controller = TextEditingController(); final url = await LocalizedDialogHelper.showWidgetDialog<String>( ref, DecoratedPlatformTextField( controller: controller, decoration: InputDecoration( labelText: localizations.extensionsManualUrlLabel, ), keyboardType: TextInputType.url, ), title: localizations.extensionsManualAction, actions: [ PlatformTextButton( child: Text(localizations.actionCancel), onPressed: () => context.pop(), ), PlatformTextButton( child: Text(localizations.actionOk), onPressed: () { final urlText = controller.text.trim(); context.pop(urlText); }, ), ], ); // controller.dispose(); if (url != null) { var usedUrl = url; if (url.length > 4) { if (!url.contains(':')) { usedUrl = 'https://$url'; } if (!url.endsWith('json')) { usedUrl = url.endsWith('/') ? '$url.maily.json' : '$url/.maily.json'; } final appExtension = await AppExtension.loadFromUrl(usedUrl); if (appExtension != null) { final currentAccount = ref.read(currentAccountProvider); ((currentAccount is RealAccount) ? currentAccount : ref.read(realAccountsProvider).first) .appExtensions = [appExtension]; if (context.mounted) { _showExtensionDetails(context, ref, url, appExtension); } await ref.read(realAccountsProvider.notifier).save(); } else if (context.mounted) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, localizations.extensionsManualLoadingError(url), ); } } else if (context.mounted) { await LocalizedDialogHelper.showTextDialog( ref, localizations.errorTitle, 'Invalid URL "$url"', ); } } } void _deactivateAllExtensions(WidgetRef ref) { final accounts = ref.read(realAccountsProvider); for (final account in accounts) { account.appExtensions = []; } ref.read(realAccountsProvider.notifier).save(); } Future<void> _reloadExtensions(BuildContext context, WidgetRef ref) async { final localizations = ref.text; final accounts = ref.read(realAccountsProvider); final domains = <_AccountDomain>[]; for (final account in accounts) { account.appExtensions = []; _addEmail(account, account.email, domains); _addHostname( account, account.mailAccount.incoming.serverConfig.hostname, domains, ); _addHostname( account, account.mailAccount.outgoing.serverConfig.hostname, domains, ); } await LocalizedDialogHelper.showWidgetDialog( ref, SingleChildScrollView( child: Column( children: [ for (final domain in domains) PlatformListTile( title: Text(domain.domain), subtitle: Text(AppExtension.urlFor(domain.domain)), trailing: FutureBuilder<AppExtension?>( future: domain.future, builder: (context, snapshot) { final data = snapshot.data; if (data != null) { domain.account?.appExtensions?.add(data); return PlatformIconButton( icon: const Icon(Icons.check), onPressed: () => _showExtensionDetails( context, ref, domain.domain, data, ), ); } else if (snapshot.connectionState == ConnectionState.done) { return const Icon(Icons.cancel_outlined); } return const PlatformProgressIndicator(); }, ), ), ], ), ), title: localizations.extensionsTitle, ); } void _addEmail( RealAccount? account, String email, List<_AccountDomain> domains, ) { _addDomain(account, email.substring(email.indexOf('@') + 1), domains); } void _addHostname( RealAccount? account, String hostname, List<_AccountDomain> domains, ) { final domainIndex = hostname.indexOf('.'); if (domainIndex != -1) { _addDomain(account, hostname.substring(domainIndex + 1), domains); } } void _addDomain( RealAccount? account, String domain, List<_AccountDomain> domains, ) { if (!domains.any((k) => k.domain == domain)) { domains .add(_AccountDomain(account, domain, AppExtension.loadFrom(domain))); } } void _showExtensionDetails( BuildContext context, WidgetRef ref, String? domainOrUrl, AppExtension data, ) { final accountSideMenu = data.accountSideMenu; final forgotPasswordAction = data.forgotPasswordAction; LocalizedDialogHelper.showWidgetDialog( ref, Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Version: ${data.version}'), if (accountSideMenu != null) ...[ const Divider(), const Text('Account side menus:'), for (final entry in accountSideMenu) Text('"${entry.getLabel('en')}": ${entry.action?.url}'), ], if (forgotPasswordAction != null) ...[ const Divider(), const Text('Forgot password:'), Text( '"${forgotPasswordAction.getLabel('en')}": ' '${forgotPasswordAction.action?.url}', ), ], if (data.signatureHtml != null) ...[ const Divider(), const Text('Signature:'), Text('${data.getSignatureHtml('en')}'), ], ], ), title: '$domainOrUrl Extension', ); } } class _AccountDomain { _AccountDomain(this.account, this.domain, this.future); final RealAccount? account; final String domain; final Future<AppExtension?> future; }
0
mirrored_repositories/enough_mail_app/lib/src/settings
mirrored_repositories/enough_mail_app/lib/src/settings/view/settings_theme_screen.dart
import 'package:enough_platform_widgets/enough_platform_widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../localization/extension.dart'; import '../../screens/base.dart'; import '../../util/localized_dialog_helper.dart'; import '../provider.dart'; import '../theme/model.dart'; import '../theme/provider.dart'; class SettingsDesignScreen extends HookConsumerWidget { const SettingsDesignScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final localizations = ref.text; final theme = Theme.of(context); final themeSettings = ref.watch( settingsProvider.select( (value) => value.themeSettings, ), ); final darkThemeStartTime = themeSettings.themeDarkStartTime; final darkThemeEndTime = themeSettings.themeDarkEndTime; final availableColors = ThemeSettings.availableColors; final defaultColor = ref.watch(defaultColorSeedProvider); void updateThemeSettings(ThemeSettings value) { final settings = ref.read(settingsProvider); ref.read(settingsProvider.notifier).update( settings.copyWith( themeSettings: value, ), ); } void updateThemeModeSettings(ThemeModeSetting? value) => updateThemeSettings( themeSettings.copyWith(themeModeSetting: value), ); return BasePage( title: localizations.designTitle, content: SingleChildScrollView( child: Material( child: SafeArea( child: Padding( padding: const EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( localizations.designSectionThemeTitle, style: theme.textTheme.titleMedium, ), PlatformRadioListTile<ThemeModeSetting>( title: Text(localizations.designThemeOptionLight), value: ThemeModeSetting.light, groupValue: themeSettings.themeModeSetting, onChanged: updateThemeModeSettings, ), PlatformRadioListTile<ThemeModeSetting>( title: Text(localizations.designThemeOptionDark), value: ThemeModeSetting.dark, groupValue: themeSettings.themeModeSetting, onChanged: updateThemeModeSettings, ), PlatformRadioListTile<ThemeModeSetting>( title: Text(localizations.designThemeOptionSystem), value: ThemeModeSetting.system, groupValue: themeSettings.themeModeSetting, onChanged: updateThemeModeSettings, ), PlatformRadioListTile<ThemeModeSetting>( title: Text(localizations.designThemeOptionCustom), value: ThemeModeSetting.custom, groupValue: themeSettings.themeModeSetting, onChanged: updateThemeModeSettings, ), if (themeSettings.themeModeSetting == ThemeModeSetting.custom) ...[ Text( localizations.designSectionCustomTitle, style: theme.textTheme.titleMedium, ), Row( children: [ PlatformTextButton( child: Text( localizations.designThemeCustomStart( darkThemeStartTime.format(context), ), ), onPressed: () async { final pickedTime = await showPlatformTimePicker( context: context, initialTime: darkThemeStartTime, ); if (pickedTime != null) { updateThemeSettings( themeSettings.copyWith( themeDarkStartTime: pickedTime, themeModeSetting: ThemeModeSetting.custom, ), ); } }, ), PlatformTextButton( child: Text( localizations.designThemeCustomEnd( darkThemeEndTime.format(context), ), ), onPressed: () async { final pickedTime = await showPlatformTimePicker( context: context, initialTime: darkThemeEndTime, ); if (pickedTime != null) { updateThemeSettings( themeSettings.copyWith( themeDarkEndTime: pickedTime, themeModeSetting: ThemeModeSetting.custom, ), ); } }, ), ], ), ], const Divider(), Text( localizations.designSectionColorTitle, style: theme.textTheme.titleMedium, ), GridView.count( crossAxisCount: 4, primary: false, shrinkWrap: true, children: [ PlatformListTile( title: CircleAvatar( backgroundColor: themeSettings.colorSchemeSeed, child: Icon(PlatformInfo.isCupertino ? CupertinoIcons.color_filter : Icons.colorize), ), onTap: () async { Color selectedColor = themeSettings.colorSchemeSeed ?? defaultColor; final result = await LocalizedDialogHelper.showWidgetDialog( ref, ColorPicker( pickerColor: themeSettings.colorSchemeSeed ?? defaultColor, onColorChanged: (value) => selectedColor = value, ), defaultActions: DialogActions.okAndCancel, ); if (result == true) { updateThemeSettings( themeSettings.copyWith( colorSchemeSeed: selectedColor, ), ); } }, ), for (final color in availableColors) PlatformListTile( title: CircleAvatar( backgroundColor: color, child: (color == themeSettings.colorSchemeSeed) ? Icon(CommonPlatformIcons.ok) : null, ), onTap: () { updateThemeSettings( themeSettings.copyWith( colorSchemeSeed: color, ), ); }, ), ], ), ], ), ), ), ), ), ); } }
0