repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/history_clear_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:routerino/routerino.dart';
class HistoryClearDialog extends StatelessWidget {
const HistoryClearDialog({super.key});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.historyClearDialog.title),
content: Text(t.dialogs.historyClearDialog.content),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
FilledButton(
onPressed: () => context.pop(true),
child: Text(t.general.delete),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/cannot_open_file_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:routerino/routerino.dart';
class CannotOpenFileDialog extends StatelessWidget {
final String path;
const CannotOpenFileDialog({required this.path, super.key});
static Future<void> open(BuildContext context, String path, void Function()? onDeleteTap) async {
if (checkPlatformIsDesktop()) {
await showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(t.dialogs.cannotOpenFile.title),
content: Text(t.dialogs.cannotOpenFile.content(file: path)),
actions: [
if (onDeleteTap != null)
TextButton(
onPressed: () {
onDeleteTap();
context.pop();
},
child: Text(t.receiveHistoryPage.entryActions.deleteFromHistory),
),
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
),
);
} else {
await context.pushBottomSheet(() => CannotOpenFileDialog(path: path));
}
}
@override
Widget build(BuildContext context) {
return CustomBottomSheet(
title: t.dialogs.cannotOpenFile.title,
description: t.dialogs.cannotOpenFile.content(file: path),
child: Center(
child: ElevatedButton(
onPressed: () => context.popUntilRoot(),
child: Text(t.general.close),
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/favorite_edit_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:localsend_app/provider/network/targeted_discovery_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/widget/dialogs/favorite_delete_dialog.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
/// A dialog to add or edit a favorite device.
class FavoriteEditDialog extends StatefulWidget {
final FavoriteDevice? favorite;
const FavoriteEditDialog({this.favorite});
@override
State<FavoriteEditDialog> createState() => _FavoriteEditDialogState();
}
class _FavoriteEditDialogState extends State<FavoriteEditDialog> with Refena {
final _ipController = TextEditingController();
final _portController = TextEditingController();
final _aliasController = TextEditingController();
bool _fetching = false;
bool _failed = false;
@override
void initState() {
super.initState();
_ipController.text = widget.favorite?.ip ?? '';
_aliasController.text = widget.favorite?.alias ?? '';
ensureRef((ref) {
_portController.text = widget.favorite?.port.toString() ?? ref.read(settingsProvider).port.toString();
});
}
@override
void dispose() {
_ipController.dispose();
_portController.dispose();
_aliasController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(widget.favorite != null ? t.dialogs.favoriteEditDialog.titleEdit : t.dialogs.favoriteEditDialog.titleAdd),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(t.dialogs.favoriteEditDialog.name),
const SizedBox(height: 5),
TextFormField(
controller: _aliasController,
decoration: InputDecoration(
hintText: t.dialogs.favoriteEditDialog.auto,
),
enabled: !_fetching,
),
const SizedBox(height: 16),
Text(t.dialogs.favoriteEditDialog.ip),
const SizedBox(height: 5),
TextFormField(
controller: _ipController,
autofocus: widget.favorite == null,
enabled: !_fetching,
),
const SizedBox(height: 16),
Text(t.dialogs.favoriteEditDialog.port),
const SizedBox(height: 5),
TextFormField(
controller: _portController,
enabled: !_fetching,
keyboardType: TextInputType.number,
),
if (widget.favorite != null) ...[
const SizedBox(height: 16),
TextButton.icon(
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.warning,
),
onPressed: () async {
final result = await showDialog<bool>(
context: context,
builder: (_) => FavoriteDeleteDialog(widget.favorite!),
);
if (mounted && result == true) {
await context.ref.redux(favoritesProvider).dispatchAsync(RemoveFavoriteAction(deviceFingerprint: widget.favorite!.fingerprint));
if (mounted) {
context.pop();
}
}
},
icon: const Icon(Icons.delete),
label: Text(t.general.delete),
),
],
if (_failed)
Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(t.general.error, style: TextStyle(color: Theme.of(context).colorScheme.warning)),
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
FilledButton(
onPressed: _fetching
? null
: () async {
if (_ipController.text.isEmpty) {
return;
}
if (_portController.text.isEmpty) {
return;
}
if (widget.favorite != null) {
// Update existing favorite
final existingFavorite = widget.favorite!;
final trimmedNewAlias = _aliasController.text.trim();
if (trimmedNewAlias.isEmpty) {
return;
}
await ref.redux(favoritesProvider).dispatchAsync(UpdateFavoriteAction(existingFavorite.copyWith(
ip: _ipController.text,
port: int.parse(_portController.text),
alias: trimmedNewAlias,
customAlias: existingFavorite.customAlias || trimmedNewAlias != existingFavorite.alias,
)));
} else {
// Add new favorite
final ip = _ipController.text;
final port = int.parse(_portController.text);
final https = ref.read(settingsProvider).https;
setState(() {
_fetching = true;
});
final result = await ref.read(targetedDiscoveryProvider).discover(ip: ip, port: port, https: https);
if (result == null) {
setState(() {
_fetching = false;
_failed = true;
});
return;
}
final name = _aliasController.text.trim();
await ref.redux(favoritesProvider).dispatchAsync(AddFavoriteAction(FavoriteDevice.fromValues(
fingerprint: result.fingerprint,
ip: _ipController.text,
port: int.parse(_portController.text),
alias: name.isEmpty ? result.alias : name,
)));
}
if (mounted) {
context.pop();
}
},
child: Text(t.general.confirm),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/favorite_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:localsend_app/provider/network/targeted_discovery_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:localsend_app/widget/dialogs/favorite_edit_dialog.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
/// A dialog showing a list of favorites
class FavoritesDialog extends StatefulWidget {
const FavoritesDialog();
@override
State<FavoritesDialog> createState() => _FavoritesDialogState();
}
class _FavoritesDialogState extends State<FavoritesDialog> with Refena {
bool _fetching = false;
bool _failed = false;
/// Checks if the device is reachable and pops the dialog with the result if it is.
Future<void> _checkConnectionToDevice(FavoriteDevice favorite) async {
setState(() {
_fetching = true;
});
final https = ref.read(settingsProvider).https;
final result = await ref.read(targetedDiscoveryProvider).discover(ip: favorite.ip, port: favorite.port, https: https);
if (result == null) {
setState(() {
_fetching = false;
_failed = true;
});
return;
}
if (!mounted) {
return;
}
context.pop(result);
}
Future<void> _showDeviceDialog([FavoriteDevice? favorite]) async {
await showDialog(context: context, builder: (_) => FavoriteEditDialog(favorite: favorite));
}
@override
Widget build(BuildContext context) {
final favorites = ref.watch(favoritesProvider);
return AlertDialog(
title: Text(t.dialogs.favoriteDialog.title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (favorites.isEmpty)
Text(
t.dialogs.favoriteDialog.noFavorites,
style: const TextStyle(color: Colors.grey),
),
for (final favorite in favorites)
Row(
children: [
Expanded(
child: TextButton(
style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),
onPressed: _fetching ? null : () async => await _checkConnectionToDevice(favorite),
child: Align(
alignment: Alignment.centerLeft,
child: Text('${favorite.alias}\n(${favorite.ip})'),
),
),
),
TextButton(
style: TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onSurface),
onPressed: _fetching ? null : () async => await _showDeviceDialog(favorite),
child: const Icon(Icons.edit),
),
],
),
if (_failed)
Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(t.general.error, style: TextStyle(color: Theme.of(context).colorScheme.warning)),
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
FilledButton(
onPressed: _showDeviceDialog,
child: Text(t.dialogs.favoriteDialog.addFavorite),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/quick_actions_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/provider/selection/selected_receiving_files_provider.dart';
import 'package:localsend_app/widget/labeled_checkbox.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
import 'package:uuid/uuid.dart';
enum _QuickAction {
counter,
random;
String get label {
switch (this) {
case _QuickAction.counter:
return t.dialogs.quickActions.counter;
case _QuickAction.random:
return t.dialogs.quickActions.random;
}
}
}
class QuickActionsDialog extends StatefulWidget {
const QuickActionsDialog({super.key});
@override
State<QuickActionsDialog> createState() => _QuickActionsDialogState();
}
class _QuickActionsDialogState extends State<QuickActionsDialog> with Refena {
_QuickAction _action = _QuickAction.counter;
// counter
String _prefix = '';
bool _padZero = false;
bool _sortBeforehand = false;
// random
final _randomUuid = const Uuid().v4();
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.quickActions.title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ToggleButtons(
isSelected: [_action == _QuickAction.counter, _action == _QuickAction.random],
onPressed: (int index) {
setState(() {
if (index == 0) {
_action = _QuickAction.counter;
} else {
_action = _QuickAction.random;
}
});
},
borderRadius: BorderRadius.circular(10),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
constraints: const BoxConstraints(minWidth: 0, minHeight: 0),
children: _QuickAction.values.map((mode) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: Text(mode.label),
);
}).toList(),
),
const SizedBox(height: 10),
if (_action == _QuickAction.counter) ...[
Text(t.dialogs.quickActions.prefix),
const SizedBox(height: 5),
TextField(
autofocus: true,
onChanged: (s) {
setState(() {
_prefix = s;
});
},
),
const SizedBox(height: 10),
LabeledCheckbox(
label: t.dialogs.quickActions.padZero,
value: _padZero,
onChanged: (b) {
setState(() {
_padZero = b == true;
});
},
),
const SizedBox(height: 5),
LabeledCheckbox(
label: t.dialogs.quickActions.sortBeforeCount,
value: _sortBeforehand,
onChanged: (b) {
setState(() {
_sortBeforehand = b == true;
});
},
),
const SizedBox(height: 10),
if (_padZero) Text('${t.general.example}: ${_prefix}04.jpg') else Text('${t.general.example}: ${_prefix}4.jpg'),
],
if (_action == _QuickAction.random) Text('${t.general.example}: $_randomUuid.jpg'),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(context).colorScheme.onPrimary,
),
onPressed: () {
switch (_action) {
case _QuickAction.counter:
ref.notifier(selectedReceivingFilesProvider).applyCounter(
prefix: _prefix,
padZero: _padZero,
sortFirst: _sortBeforehand,
);
break;
case _QuickAction.random:
ref.notifier(selectedReceivingFilesProvider).applyRandom();
break;
}
context.pop();
},
child: Text(t.general.confirm),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/quick_save_notice.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:routerino/routerino.dart';
class QuickSaveNotice extends StatelessWidget {
const QuickSaveNotice({super.key});
static Future<void> open(BuildContext context) async {
if (checkPlatformIsDesktop()) {
await showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(t.dialogs.quickSaveNotice.title),
content: Text(t.dialogs.quickSaveNotice.content),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
),
);
} else {
await context.pushBottomSheet(() => const QuickSaveNotice());
}
}
@override
Widget build(BuildContext context) {
return CustomBottomSheet(
title: t.dialogs.quickSaveNotice.title,
description: t.dialogs.quickSaveNotice.content,
child: Center(
child: ElevatedButton(
onPressed: () => context.popUntilRoot(),
child: Text(t.general.close),
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/ios_network_permission_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:routerino/routerino.dart';
import 'package:system_settings/system_settings.dart';
class IosLocalNetworkDialog extends StatelessWidget {
const IosLocalNetworkDialog({super.key});
@override
Widget build(BuildContext context) {
return CustomBottomSheet(
title: t.dialogs.localNetworkUnauthorized.title,
description: t.dialogs.localNetworkUnauthorized.description,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
),
ElevatedButton.icon(
onPressed: () async => SystemSettings.app(),
icon: const Icon(Icons.settings),
label: Text(t.dialogs.localNetworkUnauthorized.gotoSettings),
),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/favorite_delete_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:routerino/routerino.dart';
class FavoriteDeleteDialog extends StatelessWidget {
final FavoriteDevice favorite;
const FavoriteDeleteDialog(this.favorite);
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.favoriteDeleteDialog.title),
content: Text(t.dialogs.favoriteDeleteDialog.content(name: favorite.alias)),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.cancel),
),
FilledButton(
onPressed: () => context.pop(true),
child: Text(t.general.delete),
),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/no_files_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:routerino/routerino.dart';
class NoFilesDialog extends StatelessWidget {
const NoFilesDialog({super.key});
@override
Widget build(BuildContext context) {
return CustomBottomSheet(
title: t.dialogs.noFiles.title,
description: t.dialogs.noFiles.content,
child: Center(
child: FilledButton(
onPressed: () => context.popUntilRoot(),
child: Text(t.general.close),
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/text_field_tv.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/provider/tv_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
/// A normal [TextFormField] on mobile and desktop.
/// A button which opens a dialog on Android TV
class TextFieldTv extends StatefulWidget {
final String name;
final TextEditingController controller;
final ValueChanged<String> onChanged;
const TextFieldTv({
required this.name,
required this.controller,
required this.onChanged,
});
@override
State<TextFieldTv> createState() => _TextFieldTvState();
}
class _TextFieldTvState extends State<TextFieldTv> with Refena {
@override
Widget build(BuildContext context) {
final isTv = ref.watch(tvProvider);
if (isTv) {
return TextButton(
style: TextButton.styleFrom(
backgroundColor: Theme.of(context).inputDecorationTheme.fillColor,
shape: RoundedRectangleBorder(borderRadius: Theme.of(context).inputDecorationTheme.borderRadius),
foregroundColor: Theme.of(context).colorScheme.onSurface,
),
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(widget.name),
content: TextFormField(
controller: widget.controller,
textAlign: TextAlign.center,
onChanged: widget.onChanged,
autofocus: true,
onFieldSubmitted: (_) => context.pop(),
),
actions: [
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Theme.of(context).colorScheme.onPrimary,
),
onPressed: () => context.pop(),
child: Text(t.general.confirm),
)
],
);
},
);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text(widget.controller.text, style: Theme.of(context).textTheme.titleMedium),
),
);
} else {
return TextFormField(
controller: widget.controller,
textAlign: TextAlign.center,
onChanged: widget.onChanged,
);
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/no_permission_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:routerino/routerino.dart';
class NoPermissionDialog extends StatelessWidget {
const NoPermissionDialog({super.key});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.noPermission.title),
content: Text(t.dialogs.noPermission.content),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/cancel_session_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:routerino/routerino.dart';
class CancelSessionDialog extends StatelessWidget {
const CancelSessionDialog();
@override
Widget build(BuildContext context) {
return CustomBottomSheet(
title: t.dialogs.cancelSession.title,
description: t.dialogs.cancelSession.content,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
TextButton(
onPressed: () => context.pop(false),
child: Text(t.general.continueStr),
),
ElevatedButton.icon(
onPressed: () => context.pop(true),
icon: const Icon(Icons.close),
label: Text(t.general.cancel),
),
],
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/qr_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/state/send/web/web_send_state.dart';
import 'package:localsend_app/provider/network/server/server_provider.dart';
import 'package:localsend_app/theme.dart';
import 'package:pretty_qr_code/pretty_qr_code.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
class QrDialog extends StatelessWidget {
final String data;
final bool listenIncomingWebSendRequests;
const QrDialog({
required this.data,
this.listenIncomingWebSendRequests = false,
});
@override
Widget build(BuildContext context) {
final WebSendState? webSendState;
if (listenIncomingWebSendRequests) {
webSendState = context.ref.watch(serverProvider.select((s) => s?.webSendState));
} else {
webSendState = null;
}
return AlertDialog(
title: Text(t.dialogs.qr.title),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
width: 200,
height: 200,
child: PrettyQrView.data(
errorCorrectLevel: QrErrorCorrectLevel.Q,
data: data,
decoration: PrettyQrDecoration(
shape: PrettyQrSmoothSymbol(
roundFactor: 0,
color: Theme.of(context).colorScheme.onSurface,
),
),
),
),
),
const SizedBox(height: 10),
Text(data, textAlign: TextAlign.center),
if (listenIncomingWebSendRequests && webSendState != null)
Builder(
builder: (context) {
final pending = webSendState?.sessions.values.fold<int>(0, (prev, curr) => prev + (curr.responseHandler != null ? 1 : 0)) ?? 0;
if (pending != 0) {
return Padding(
padding: const EdgeInsets.only(top: 5),
child: Text(
t.webSharePage.pendingRequests(n: pending),
style: TextStyle(color: Theme.of(context).colorScheme.warning),
textAlign: TextAlign.center,
),
);
} else {
return Container();
}
},
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/encryption_disabled_notice.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';
import 'package:routerino/routerino.dart';
class EncryptionDisabledNotice extends StatelessWidget {
const EncryptionDisabledNotice({super.key});
static Future<void> open(BuildContext context) async {
if (checkPlatformIsDesktop()) {
await showDialog(
context: context,
builder: (_) => AlertDialog(
title: Text(t.dialogs.encryptionDisabledNotice.title),
content: Text(t.dialogs.encryptionDisabledNotice.content),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
),
);
} else {
await context.pushBottomSheet(() => const EncryptionDisabledNotice());
}
}
@override
Widget build(BuildContext context) {
return CustomBottomSheet(
title: t.dialogs.encryptionDisabledNotice.title,
description: t.dialogs.encryptionDisabledNotice.content,
child: Center(
child: ElevatedButton(
onPressed: () => context.popUntilRoot(),
child: Text(t.general.close),
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/error_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:routerino/routerino.dart';
class ErrorDialog extends StatelessWidget {
final String error;
const ErrorDialog({required this.error, super.key});
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.errorDialog.title),
content: SelectableText(error),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/dialogs/send_mode_help_dialog.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:routerino/routerino.dart';
class SendModeHelpDialog extends StatelessWidget {
const SendModeHelpDialog();
@override
Widget build(BuildContext context) {
return AlertDialog(
title: Text(t.dialogs.sendModeHelp.title),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_SendModeItem(
mode: t.sendTab.sendModes.single,
explanation: t.dialogs.sendModeHelp.single,
),
const SizedBox(height: 10),
_SendModeItem(
mode: t.sendTab.sendModes.multiple,
explanation: t.dialogs.sendModeHelp.multiple,
),
const SizedBox(height: 10),
_SendModeItem(
mode: t.sendTab.sendModes.link,
explanation: t.dialogs.sendModeHelp.link,
),
],
),
actions: [
TextButton(
onPressed: () => context.pop(),
child: Text(t.general.close),
)
],
);
}
}
class _SendModeItem extends StatelessWidget {
final String mode;
final String explanation;
const _SendModeItem({
required this.mode,
required this.explanation,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(mode, style: const TextStyle(fontWeight: FontWeight.bold)),
Text(explanation),
],
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/watcher/life_cycle_watcher.dart | import 'package:flutter/material.dart';
class LifeCycleWatcher extends StatefulWidget {
final Widget child;
final void Function(AppLifecycleState state) onChangedState;
const LifeCycleWatcher({required this.child, required this.onChangedState, super.key});
@override
State<LifeCycleWatcher> createState() => _LifeCycleWatcherState();
}
class _LifeCycleWatcherState extends State<LifeCycleWatcher> with WidgetsBindingObserver {
@override
Widget build(BuildContext context) {
return widget.child;
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
widget.onChangedState(state);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/watcher/window_watcher.dart | import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:localsend_app/provider/animation_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/provider/window_dimensions_provider.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/native/tray_helper.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:window_manager/window_manager.dart';
final _logger = Logger('WindowWatcher');
class WindowWatcher extends StatefulWidget {
final Widget child;
const WindowWatcher({
required this.child,
super.key,
});
@override
State<WindowWatcher> createState() => _WindowWatcherState();
static Future<void> closeWindow(BuildContext context) async {
final state = context.findAncestorStateOfType<_WindowWatcherState>();
await state?.onWindowClose();
}
}
class _WindowWatcherState extends State<WindowWatcher> with WindowListener, Refena {
static WindowDimensionsController? _dimensionsController;
static Stopwatch s = Stopwatch();
WindowDimensionsController _ensureDimensionsProvider() => ref.watch(windowDimensionProvider);
@override
Widget build(BuildContext context) {
_dimensionsController ??= _ensureDimensionsProvider();
s.start();
return widget.child;
}
@override
void initState() {
super.initState();
windowManager.addListener(this);
if (checkPlatformIsDesktop()) {
WidgetsBinding.instance.addPostFrameCallback((_) async {
try {
// always handle close actions manually
await windowManager.setPreventClose(true);
} catch (e) {
_logger.warning('Failed to set prevent close', e);
}
});
}
}
@override
void dispose() {
windowManager.removeListener(this);
super.dispose();
}
//Linux alternative for onWindowMoved and onWindowResized
@override
Future<void> onWindowMove() async {
if (checkPlatform([TargetPlatform.linux]) && s.elapsedMilliseconds >= 600) {
s.reset();
final windowOffset = await windowManager.getPosition();
final windowSize = await windowManager.getSize();
await _dimensionsController?.storeDimensions(windowOffset: windowOffset, windowSize: windowSize);
}
}
@override
Future<void> onWindowMoved() async {
final windowOffset = await windowManager.getPosition();
await _dimensionsController?.storePosition(windowOffset: windowOffset);
}
@override
Future<void> onWindowResized() async {
final windowSize = await windowManager.getSize();
await _dimensionsController?.storeSize(windowSize: windowSize);
}
@override
Future<void> onWindowClose() async {
final windowOffset = await windowManager.getPosition();
final windowSize = await windowManager.getSize();
await _dimensionsController?.storeDimensions(windowOffset: windowOffset, windowSize: windowSize);
if (!checkPlatformIsDesktop()) {
return;
}
try {
if (ref.read(settingsProvider).minimizeToTray) {
await hideToTray();
} else {
await destroyTray();
exit(0);
}
} catch (e) {
_logger.warning('Failed to close window', e);
}
}
@override
void onWindowFocus() {
// call set state according to window_manager README
setState(() {});
}
@override
void onWindowMinimize() {
ref.notifier(sleepProvider).setState((_) => true);
}
@override
void onWindowRestore() {
ref.notifier(sleepProvider).setState((_) => false);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/watcher/tray_watcher.dart | import 'dart:io';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/native/tray_helper.dart';
import 'package:tray_manager/tray_manager.dart';
class TrayWatcher extends StatefulWidget {
final Widget child;
const TrayWatcher({required this.child, super.key});
@override
State<TrayWatcher> createState() => _TrayWatcherState();
}
class _TrayWatcherState extends State<TrayWatcher> with TrayListener {
@override
Widget build(BuildContext context) {
return widget.child;
}
@override
void initState() {
super.initState();
trayManager.addListener(this);
}
@override
void dispose() {
trayManager.removeListener(this);
super.dispose();
}
@override
void onTrayIconMouseDown() async {
if (checkPlatform([TargetPlatform.macOS])) {
await trayManager.popUpContextMenu();
} else {
await showFromTray();
}
}
@override
void onTrayIconRightMouseDown() async {
await trayManager.popUpContextMenu();
}
@override
void onTrayMenuItemClick(MenuItem menuItem) async {
final entry = TrayEntry.values.firstWhereOrNull((e) => e.name == menuItem.key);
switch (entry) {
case TrayEntry.open:
await showFromTray();
break;
case TrayEntry.close:
exit(0);
default:
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/watcher/shortcut_watcher.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:localsend_app/util/native/file_picker.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/widget/watcher/window_watcher.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
class ShortcutWatcher extends StatelessWidget {
final Widget child;
const ShortcutWatcher({required this.child});
@override
Widget build(BuildContext context) {
return Shortcuts(
shortcuts: {
// The select button on AndroidTV needs this to work
LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(),
// Add Control+Q binding for Linux
// https://github.com/localsend/localsend/issues/194
if (checkPlatform([TargetPlatform.linux])) LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyQ): _ExitAppIntent(),
// Add Command+W to close the window for macOS
if (checkPlatform([TargetPlatform.macOS])) LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.keyW): _CloseWindowIntent(),
LogicalKeySet(LogicalKeyboardKey.escape): _PopPageIntent(),
// Control+V and Command+V
LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyV): _PasteIntent(),
LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.keyV): _PasteIntent(),
},
child: Actions(
actions: {
_ExitAppIntent: CallbackAction(onInvoke: (_) => exit(0)),
_PopPageIntent: CallbackAction(onInvoke: (_) async => Navigator.of(Routerino.context).maybePop()),
_PasteIntent: CallbackAction(onInvoke: (_) async {
await context.ref.dispatchAsync(PickFileAction(option: FilePickerOption.clipboard, context: context));
return null;
}),
_CloseWindowIntent: CallbackAction<_CloseWindowIntent>(
onInvoke: (_) async {
await WindowWatcher.closeWindow(context);
return null;
},
),
},
child: child,
),
);
}
}
class _ExitAppIntent extends Intent {}
class _PopPageIntent extends Intent {}
class _PasteIntent extends Intent {}
class _CloseWindowIntent extends Intent {}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/animations/initial_slide_transition.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/sleep.dart';
class InitialSlideTransition extends StatefulWidget {
final Widget child;
final Offset origin;
final Offset destination;
final Curve curve;
final Duration duration;
final Duration delay;
const InitialSlideTransition({
required this.child,
this.origin = Offset.zero,
this.destination = Offset.zero,
this.curve = Curves.easeOutCubic,
required this.duration,
this.delay = Duration.zero,
super.key,
});
@override
State<InitialSlideTransition> createState() => _InitialSlideTransitionState();
}
class _InitialSlideTransitionState extends State<InitialSlideTransition> {
late Offset _offset;
@override
void initState() {
super.initState();
_offset = widget.origin;
WidgetsBinding.instance.addPostFrameCallback((_) async {
await sleepAsync(widget.delay.inMilliseconds);
if (!mounted) {
return;
}
setState(() {
_offset = widget.destination;
});
});
}
@override
Widget build(BuildContext context) {
return AnimatedSlide(
offset: _offset,
curve: widget.curve,
duration: widget.duration,
child: widget.child,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/widget | mirrored_repositories/localsend/app/lib/widget/animations/initial_fade_transition.dart | import 'package:flutter/material.dart';
import 'package:localsend_app/util/sleep.dart';
class InitialFadeTransition extends StatefulWidget {
final Widget child;
final Duration duration;
final Duration delay;
const InitialFadeTransition({
required this.child,
required this.duration,
this.delay = Duration.zero,
super.key,
});
@override
State<InitialFadeTransition> createState() => _InitialFadeTransitionState();
}
class _InitialFadeTransitionState extends State<InitialFadeTransition> {
double _opacity = 0;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
await sleepAsync(widget.delay.inMilliseconds);
if (!mounted) {
return;
}
setState(() {
_opacity = 1;
});
});
}
@override
Widget build(BuildContext context) {
return AnimatedOpacity(
opacity: _opacity,
duration: widget.duration,
child: widget.child,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/window_dimensions_provider.dart | import 'dart:ui';
import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:screen_retriever/screen_retriever.dart';
import 'package:window_manager/window_manager.dart';
// Records are a better alternative, but they are currently experimental
typedef WindowDimensions = Map<String, OffsetBase?>;
final windowDimensionProvider = Provider<WindowDimensionsController>((ref) {
return WindowDimensionsController(ref.read(persistenceProvider));
});
const Size _minimalSize = Size(400, 500);
const Size _defaultSize = Size(900, 600);
class WindowDimensionsController {
final PersistenceService _service;
WindowDimensionsController(this._service);
/// Sets window position & size according to saved settings.
Future<void> initDimensionsConfiguration() async {
await WindowManager.instance.setMinimumSize(_minimalSize);
final primaryDisplay = await ScreenRetriever.instance.getPrimaryDisplay();
final hasEnoughWidth = (primaryDisplay.visibleSize ?? primaryDisplay.size).width >= 1200;
// load saved Window placement and preferences
final useSavedPlacement = _service.getSaveWindowPlacement();
final persistedDimensions = _service.getWindowLastDimensions();
// if [savePlacement is false], both values will be [set to null]
final Size? persistedSize = useSavedPlacement ? persistedDimensions['size'] as Size? : null;
final Offset? persistedOffset = useSavedPlacement ? persistedDimensions['position'] as Offset? : null;
// Checks if the last known position is valid
bool foundInScreen = await isInScreenBounds(persistedOffset);
// settings applied accordingly if [save option is enabled] and if [persisted values are valid]
if (foundInScreen) {
await WindowManager.instance.setSize(persistedSize ?? (hasEnoughWidth ? _defaultSize : _minimalSize));
} else {
await WindowManager.instance.setSize(hasEnoughWidth ? _defaultSize : _minimalSize);
}
if (persistedOffset == null || !foundInScreen) {
await WindowManager.instance.center();
} else {
await WindowManager.instance.setPosition(persistedOffset);
}
}
Future<bool> isInScreenBounds(Offset? windowOffset) async {
if (windowOffset != null) {
Size screenTotal = const Size(0.0, 0.0);
double height = 0;
List<Display> displays = await ScreenRetriever.instance.getAllDisplays();
for (final display in displays) {
if (display.size.height > height) {
height = display.size.height - height;
}
screenTotal += Offset(display.size.width, height);
if (screenTotal.contains(windowOffset)) {
return true;
}
}
}
return false;
}
Future<void> storeDimensions({
required Offset windowOffset,
required Size windowSize,
}) async {
if (await isInScreenBounds(windowOffset)) {
await _service.setWindowOffsetX(windowOffset.dx);
await _service.setWindowOffsetY(windowOffset.dy);
await _service.setWindowHeight(windowSize.height);
await _service.setWindowWidth(windowSize.width);
}
}
Future<void> storePosition({required Offset windowOffset}) async {
if (await isInScreenBounds(windowOffset)) {
await _service.setWindowOffsetX(windowOffset.dx);
await _service.setWindowOffsetY(windowOffset.dy);
}
}
Future<void> storeSize({required Size windowSize}) async {
await _service.setWindowHeight(windowSize.height);
await _service.setWindowWidth(windowSize.width);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/animation_provider.dart | import 'package:flutter/scheduler.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
/// If true, then animations are disabled.
/// Used when the app is in the background.
final sleepProvider = StateProvider<bool>((ref) {
return false;
}, debugLabel: 'sleepProvider');
/// If false, then animations are disabled.
final animationProvider = ViewProvider<bool>((ref) {
final sleeping = ref.watch(sleepProvider);
final enableAnimations = ref.watch(settingsProvider.select((s) => s.enableAnimations));
final animations = enableAnimations && !sleeping;
timeDilation = animations ? 1.0 : 0.00001;
if (animations) {
setDefaultRouteTransition();
} else {
Routerino.transition = RouterinoTransition.noTransition;
}
return animations;
});
void setDefaultRouteTransition() {
// use the "slide" transition for desktop
if (checkPlatformIsDesktop()) {
Routerino.transition = RouterinoTransition.cupertino;
} else {
Routerino.transition = RouterinoTransition.material;
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/device_info_provider.dart | import 'package:collection/collection.dart';
import 'package:common/common.dart';
import 'package:localsend_app/provider/local_ip_provider.dart';
import 'package:localsend_app/provider/network/server/server_provider.dart';
import 'package:localsend_app/provider/security_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/native/device_info_helper.dart';
import 'package:refena_flutter/refena_flutter.dart';
final deviceRawInfoProvider = Provider<DeviceInfoResult>((ref) {
throw Exception('deviceRawInfoProvider not initialized');
});
final deviceInfoProvider = ViewProvider<DeviceInfoResult>((ref) {
final (deviceType, deviceModel) = ref.watch(settingsProvider.select((state) => (state.deviceType, state.deviceModel)));
final rawInfo = ref.watch(deviceRawInfoProvider);
return DeviceInfoResult(
deviceType: deviceType ?? rawInfo.deviceType,
deviceModel: deviceModel ?? rawInfo.deviceModel,
androidSdkInt: rawInfo.androidSdkInt,
);
});
final deviceFullInfoProvider = ViewProvider((ref) {
final networkInfo = ref.watch(localIpProvider);
final serverState = ref.watch(serverProvider);
final rawInfo = ref.watch(deviceInfoProvider);
final securityContext = ref.read(securityProvider);
return Device(
ip: networkInfo.localIps.firstOrNull ?? '-',
version: protocolVersion,
port: serverState?.port ?? -1,
alias: serverState?.alias ?? '-',
https: serverState?.https ?? true,
fingerprint: securityContext.certificateHash,
deviceModel: rawInfo.deviceModel,
deviceType: rawInfo.deviceType,
download: serverState?.webSendState != null,
);
});
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/version_provider.dart | import 'package:package_info_plus/package_info_plus.dart';
import 'package:refena_flutter/refena_flutter.dart';
final versionProvider = FutureProvider((ref) async {
final info = await PackageInfo.fromPlatform();
return '${info.version} (${info.buildNumber})';
}, debugLabel: 'VersionProvider');
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/receive_history_provider.dart | import 'package:common/common.dart';
import 'package:localsend_app/model/persistence/receive_history_entry.dart';
import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
/// This provider stores the history of received files.
/// It automatically saves the history to the device's storage.
final receiveHistoryProvider = ReduxProvider<ReceiveHistoryService, List<ReceiveHistoryEntry>>((ref) {
return ReceiveHistoryService(ref.read(persistenceProvider));
});
class ReceiveHistoryService extends ReduxNotifier<List<ReceiveHistoryEntry>> {
final PersistenceService _persistence;
ReceiveHistoryService(this._persistence);
@override
List<ReceiveHistoryEntry> init() => _persistence.getReceiveHistory();
}
/// Adds a history entry.
class AddHistoryEntryAction extends AsyncReduxAction<ReceiveHistoryService, List<ReceiveHistoryEntry>> {
final String entryId;
final String fileName;
final FileType fileType;
final String? path;
final bool savedToGallery;
final int fileSize;
final String senderAlias;
final DateTime timestamp;
AddHistoryEntryAction({
required this.entryId,
required this.fileName,
required this.fileType,
required this.path,
required this.savedToGallery,
required this.fileSize,
required this.senderAlias,
required this.timestamp,
});
@override
Future<List<ReceiveHistoryEntry>> reduce() async {
if (!notifier._persistence.isSaveToHistory()) {
return state;
}
final updated = [
ReceiveHistoryEntry(
id: entryId,
fileName: fileName,
fileType: fileType,
path: path,
savedToGallery: savedToGallery,
fileSize: fileSize,
senderAlias: senderAlias,
timestamp: timestamp,
),
...state,
].take(200).toList();
await notifier._persistence.setReceiveHistory(updated);
return updated;
}
}
/// Removes a history entry.
class RemoveHistoryEntryAction extends AsyncReduxAction<ReceiveHistoryService, List<ReceiveHistoryEntry>> {
final String entryId;
RemoveHistoryEntryAction(this.entryId);
@override
Future<List<ReceiveHistoryEntry>> reduce() async {
final index = state.indexWhere((e) => e.id == entryId);
if (index == -1) {
return state;
}
final updated = [...state]..removeAt(index);
await notifier._persistence.setReceiveHistory(updated);
return updated;
}
}
/// Removes all history entries.
class RemoveAllHistoryEntriesAction extends AsyncReduxAction<ReceiveHistoryService, List<ReceiveHistoryEntry>> {
@override
Future<List<ReceiveHistoryEntry>> reduce() async {
await notifier._persistence.setReceiveHistory([]);
return [];
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/settings_provider.dart | import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/color_mode.dart';
import 'package:localsend_app/model/send_mode.dart';
import 'package:localsend_app/model/state/settings_state.dart';
import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
final settingsProvider = NotifierProvider<SettingsService, SettingsState>((ref) {
return SettingsService(ref.read(persistenceProvider));
});
class SettingsService extends PureNotifier<SettingsState> {
final PersistenceService _persistence;
SettingsService(this._persistence);
@override
SettingsState init() => SettingsState(
showToken: _persistence.getShowToken(),
alias: _persistence.getAlias(),
theme: _persistence.getTheme(),
colorMode: _persistence.getColorMode(),
locale: _persistence.getLocale(),
port: _persistence.getPort(),
multicastGroup: _persistence.getMulticastGroup(),
destination: _persistence.getDestination(),
saveToGallery: _persistence.isSaveToGallery(),
saveToHistory: _persistence.isSaveToHistory(),
quickSave: _persistence.isQuickSave(),
autoFinish: _persistence.isAutoFinish(),
minimizeToTray: _persistence.isMinimizeToTray(),
launchAtStartup: _persistence.isLaunchAtStartup(),
autoStartLaunchMinimized: _persistence.isAutoStartLaunchMinimized(),
https: _persistence.isHttps(),
sendMode: _persistence.getSendMode(),
saveWindowPlacement: _persistence.getSaveWindowPlacement(),
enableAnimations: _persistence.getEnableAnimations(),
deviceType: _persistence.getDeviceType(),
deviceModel: _persistence.getDeviceModel(),
shareViaLinkAutoAccept: _persistence.getShareViaLinkAutoAccept(),
);
Future<void> setAlias(String alias) async {
await _persistence.setAlias(alias);
state = state.copyWith(
alias: alias,
);
}
Future<void> setTheme(ThemeMode theme) async {
await _persistence.setTheme(theme);
state = state.copyWith(
theme: theme,
);
}
Future<void> setColorMode(ColorMode mode) async {
await _persistence.setColorMode(mode);
state = state.copyWith(
colorMode: mode,
);
}
Future<void> setLocale(AppLocale? locale) async {
await _persistence.setLocale(locale);
state = state.copyWith(
locale: locale,
);
}
Future<void> setPort(int port) async {
await _persistence.setPort(port);
state = state.copyWith(
port: port,
);
}
Future<void> setMulticastGroup(String group) async {
await _persistence.setMulticastGroup(group);
state = state.copyWith(
multicastGroup: group,
);
}
Future<void> setDestination(String? destination) async {
await _persistence.setDestination(destination);
state = state.copyWith(
destination: destination,
);
}
Future<void> setSaveToGallery(bool saveToGallery) async {
await _persistence.setSaveToGallery(saveToGallery);
state = state.copyWith(
saveToGallery: saveToGallery,
);
}
Future<void> setSaveToHistory(bool saveToHistory) async {
await _persistence.setSaveToHistory(saveToHistory);
state = state.copyWith(
saveToHistory: saveToHistory,
);
}
Future<void> setQuickSave(bool quickSave) async {
await _persistence.setQuickSave(quickSave);
state = state.copyWith(
quickSave: quickSave,
);
}
Future<void> setAutoFinish(bool autoFinish) async {
await _persistence.setAutoFinish(autoFinish);
state = state.copyWith(
autoFinish: autoFinish,
);
}
Future<void> setMinimizeToTray(bool minimizeToTray) async {
await _persistence.setMinimizeToTray(minimizeToTray);
state = state.copyWith(
minimizeToTray: minimizeToTray,
);
}
Future<void> setLaunchAtStartup(bool launchAtStartup) async {
await _persistence.setLaunchAtStartup(launchAtStartup);
state = state.copyWith(
launchAtStartup: launchAtStartup,
);
}
Future<void> setAutoStartLaunchMinimized(bool launchMinimized) async {
await _persistence.setAutoStartLaunchMinimized(launchMinimized);
state = state.copyWith(
autoStartLaunchMinimized: launchMinimized,
);
}
Future<void> setHttps(bool https) async {
await _persistence.setHttps(https);
state = state.copyWith(
https: https,
);
}
Future<void> setSendMode(SendMode mode) async {
await _persistence.setSendMode(mode);
state = state.copyWith(
sendMode: mode,
);
}
Future<void> setSaveWindowPlacement(bool savePlacement) async {
await _persistence.setSaveWindowPlacement(savePlacement);
state = state.copyWith(
saveWindowPlacement: savePlacement,
);
}
Future<void> setEnableAnimations(bool enableAnimations) async {
await _persistence.setEnableAnimations(enableAnimations);
state = state.copyWith(
enableAnimations: enableAnimations,
);
}
Future<void> setDeviceType(DeviceType deviceType) async {
await _persistence.setDeviceType(deviceType);
state = state.copyWith(
deviceType: deviceType,
);
}
Future<void> setDeviceModel(String deviceModel) async {
await _persistence.setDeviceModel(deviceModel);
state = state.copyWith(
deviceModel: deviceModel,
);
}
Future<void> setShareViaLinkAutoAccept(bool shareViaLinkAutoAccept) async {
await _persistence.setShareViaLinkAutoAccept(shareViaLinkAutoAccept);
state = state.copyWith(
shareViaLinkAutoAccept: shareViaLinkAutoAccept,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/local_ip_provider.dart | import 'dart:async';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:localsend_app/model/state/network_state.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:logging/logging.dart';
import 'package:network_info_plus/network_info_plus.dart' as plugin;
import 'package:refena_flutter/refena_flutter.dart';
final _logger = Logger('NetworkInfo');
final localIpProvider = ReduxProvider<LocalIpService, NetworkState>((ref) {
return LocalIpService();
});
StreamSubscription? _subscription;
class LocalIpService extends ReduxNotifier<NetworkState> {
LocalIpService();
@override
NetworkState init() {
return const NetworkState(
localIps: [],
initialized: false,
);
}
@override
get initialAction => InitLocalIpAction();
}
/// Fetches the local IP address and registers a listener to update the IP address
class InitLocalIpAction extends ReduxAction<LocalIpService, NetworkState> {
@override
NetworkState reduce() {
if (!kIsWeb) {
// ignore: discarded_futures
_subscription?.cancel();
if (checkPlatform([TargetPlatform.windows])) {
// https://github.com/localsend/localsend/issues/12
_subscription = Stream.periodic(const Duration(seconds: 5), (_) {}).listen((_) async {
await dispatchAsync(_FetchLocalIpAction());
});
} else {
_subscription = Connectivity().onConnectivityChanged.listen((_) async {
await dispatchAsync(_FetchLocalIpAction());
});
}
}
return state;
}
@override
void after() {
// ignore: discarded_futures
dispatchAsync(_FetchLocalIpAction());
}
}
class _FetchLocalIpAction extends AsyncReduxAction<LocalIpService, NetworkState> {
@override
Future<NetworkState> reduce() async {
return NetworkState(
localIps: await _getIp(),
initialized: true,
);
}
}
Future<List<String>> _getIp() async {
final info = plugin.NetworkInfo();
String? ip;
try {
ip = await info.getWifiIP();
} catch (e) {
_logger.warning('Failed to get wifi IP', e);
}
List<String> nativeResult = [];
if (!kIsWeb) {
try {
// fallback with dart:io NetworkInterface
final result = (await NetworkInterface.list()).map((networkInterface) => networkInterface.addresses).expand((ip) => ip);
nativeResult = result.where((ip) => ip.type == InternetAddressType.IPv4).map((address) => address.address).toList();
} catch (e, st) {
_logger.info('Failed to get IP from dart:io', e, st);
}
}
final addresses = rankIpAddresses(nativeResult, ip);
_logger.info('Network state: $addresses');
return addresses;
}
List<String> rankIpAddresses(List<String> nativeResult, String? thirdPartyResult) {
if (thirdPartyResult == null) {
// only take the list
return nativeResult._rankIpAddresses(null);
} else if (nativeResult.isEmpty) {
// only take the first IP from third party library
return [thirdPartyResult];
} else if (thirdPartyResult.endsWith('.1')) {
// merge
return {thirdPartyResult, ...nativeResult}.toList()._rankIpAddresses(null);
} else {
// merge but prefer result from third party library
return {thirdPartyResult, ...nativeResult}.toList()._rankIpAddresses(thirdPartyResult);
}
}
/// Sorts Ip addresses with first being the most likely primary local address
/// Currently,
/// - sorts ending with ".1" last
/// - primary is always first
extension ListIpExt on List<String> {
List<String> _rankIpAddresses(String? primary) {
return sorted((a, b) {
int scoreA = a == primary ? 10 : (a.endsWith('.1') ? 0 : 1);
int scoreB = b == primary ? 10 : (b.endsWith('.1') ? 0 : 1);
return scoreB.compareTo(scoreA);
});
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/apk_provider.dart | import 'dart:io';
import 'package:device_apps/device_apps.dart';
import 'package:localsend_app/provider/param/apk_provider_param.dart';
import 'package:localsend_app/provider/param/cached_apk_provider_param.dart';
import 'package:refena_flutter/refena_flutter.dart';
final apkSearchParamProvider = StateProvider<ApkProviderParam>(
(ref) => const ApkProviderParam(
query: '',
includeSystemApps: false,
onlyAppsWithLaunchIntent: true,
),
);
final apkProvider = ViewProvider<AsyncValue<List<Application>>>((ref) {
final param = ref.watch(apkSearchParamProvider);
return ref
.watch(_apkProvider(CachedApkProviderParam(
includeSystemApps: param.includeSystemApps,
onlyAppsWithLaunchIntent: param.onlyAppsWithLaunchIntent,
)))
.maybeWhen(
data: (apps) {
final query = param.query.trim().toLowerCase();
if (query.isNotEmpty) {
apps = apps.where((a) => a.appName.toLowerCase().contains(query) || a.packageName.contains(query)).toList();
}
apps.sort((a, b) => a.appName.compareTo(b.appName));
return AsyncValue<List<Application>>.data(apps);
},
orElse: () => const AsyncValue<List<Application>>.loading(),
);
});
final apkSizeProvider = FutureFamilyProvider<int, String>((_, path) {
return File(path).length();
});
/// Provides a list of APKs which is cached
final _apkProvider = FutureFamilyProvider<List<Application>, CachedApkProviderParam>((_, param) {
return DeviceApps.getInstalledApplications(
includeSystemApps: param.includeSystemApps,
onlyAppsWithLaunchIntent: param.onlyAppsWithLaunchIntent,
includeAppIcons: true,
);
});
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/app_arguments_provider.dart | import 'package:refena_flutter/refena_flutter.dart';
/// Contains the arguments with which the app was started.
final appArgumentsProvider = Provider(
(ref) => <String>[],
debugLabel: 'appArgumentsProvider',
);
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/progress_provider.dart | import 'package:refena_flutter/refena_flutter.dart';
/// A provider holding the progress of the send process.
/// It is implemented as [ChangeNotifier] for performance reasons.
final progressProvider = ChangeNotifierProvider((ref) => ProgressNotifier());
class ProgressNotifier extends ChangeNotifier {
final _progressMap = <String, Map<String, double>>{}; // session id -> (file id -> 0..1)
void setProgress({required String sessionId, required String fileId, required double progress}) {
Map<String, double>? progressMap = _progressMap[sessionId];
if (progressMap == null) {
progressMap = {};
_progressMap[sessionId] = progressMap;
}
progressMap[fileId] = progress;
notifyListeners();
}
double getProgress({required String sessionId, required String fileId}) {
return _progressMap[sessionId]?[fileId] ?? 0.0;
}
int getFinishedCount(String sessionId) {
final progressMap = _progressMap[sessionId];
if (progressMap == null) {
return 0;
}
return progressMap.values.fold(0, (prev, curr) => curr == 1 ? prev + 1 : prev);
}
void removeSession(String sessionId) {
_progressMap.remove(sessionId);
notifyListeners();
}
void removeAllSessions() {
_progressMap.clear();
notifyListeners();
}
/// Only for debug purposes
Map<String, Map<String, double>> getData() {
return _progressMap;
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/favorites_provider.dart | import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
/// This provider stores the list of favorite devices.
/// It automatically saves the list to the device's storage.
final favoritesProvider = ReduxProvider<FavoritesService, List<FavoriteDevice>>((ref) {
return FavoritesService(ref.read(persistenceProvider));
});
class FavoritesService extends ReduxNotifier<List<FavoriteDevice>> {
final PersistenceService _persistence;
FavoritesService(this._persistence);
@override
List<FavoriteDevice> init() => _persistence.getFavorites();
}
/// Adds a favorite device.
class AddFavoriteAction extends AsyncReduxAction<FavoritesService, List<FavoriteDevice>> {
final FavoriteDevice device;
AddFavoriteAction(this.device);
@override
Future<List<FavoriteDevice>> reduce() async {
final updated = List<FavoriteDevice>.unmodifiable([
...state,
device,
]);
await notifier._persistence.setFavorites(updated);
return updated;
}
}
/// Updates a favorite device.
class UpdateFavoriteAction extends AsyncReduxAction<FavoritesService, List<FavoriteDevice>> {
final FavoriteDevice device;
UpdateFavoriteAction(this.device);
@override
Future<List<FavoriteDevice>> reduce() async {
final index = state.indexWhere((e) => e.id == device.id);
if (index == -1) {
// Unknown device
return state;
}
final updated = List<FavoriteDevice>.unmodifiable(<FavoriteDevice>[
...state,
]..replaceRange(index, index + 1, [device]));
await notifier._persistence.setFavorites(updated);
return updated;
}
}
/// Removes a favorite device.
class RemoveFavoriteAction extends AsyncReduxAction<FavoritesService, List<FavoriteDevice>> {
final String deviceFingerprint;
RemoveFavoriteAction({
required this.deviceFingerprint,
});
@override
Future<List<FavoriteDevice>> reduce() async {
final index = state.indexWhere((e) => e.fingerprint == deviceFingerprint);
if (index == -1) {
// Unknown device
return state;
}
final updated = List<FavoriteDevice>.unmodifiable(<FavoriteDevice>[
...state,
]..removeAt(index));
await notifier._persistence.setFavorites(updated);
return updated;
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/tv_provider.dart | import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/services.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:refena_flutter/refena_flutter.dart';
final tvProvider = Provider<bool>((_) => throw Exception('tvProvider not initialized'), debugLabel: 'tvProvider');
/// Returns true, if this device is a TV.
/// Currently, only supports Android TV.
Future<bool> checkIfTv() async {
if (checkPlatform([TargetPlatform.android])) {
DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
return androidInfo.systemFeatures.contains('android.software.leanback');
} else {
return false;
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/purchase_provider.dart | import 'dart:async';
import 'package:collection/collection.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:localsend_app/model/state/purchase_state.dart';
import 'package:refena_flutter/refena_flutter.dart';
final purchaseProvider = ReduxProvider<PurchaseService, PurchaseState>((ref) {
return PurchaseService();
});
class PurchaseService extends ReduxNotifier<PurchaseState> {
@override
PurchaseState init() => const PurchaseState(
prices: {},
purchases: {},
pending: false,
);
}
class InitPurchaseStream extends AsyncReduxAction<PurchaseService, PurchaseState> {
final listening = Completer<void>();
@override
Future<PurchaseState> reduce() async {
Future.delayed(Duration.zero, () => listening.complete());
await for (final event in InAppPurchase.instance.purchaseStream) {
for (final purchase in event) {
await dispatchAsync(_HandlePurchaseUpdate(purchase));
}
}
return state;
}
}
class FetchPricesAndPurchasesAction extends AsyncReduxAction<PurchaseService, PurchaseState> {
@override
Future<PurchaseState> reduce() async {
if (state.prices.isNotEmpty) {
emitMessage('Already fetched');
return state;
}
try {
await dispatchAsync(FetchPricesAction());
} catch (_) {}
try {
await dispatchAsync(PurchaseRestoreAction());
} catch (_) {}
return state;
}
}
/// Fetches prices for all products.
/// They come from the platform's store and vary by country.
class FetchPricesAction extends AsyncReduxAction<PurchaseService, PurchaseState> {
@override
Future<PurchaseState> reduce() async {
final response = await InAppPurchase.instance.queryProductDetails(PurchaseItem.values.map((e) => e.platformProductId).toSet());
final priceMap = <PurchaseItem, String>{};
for (final product in response.productDetails) {
final item = PurchaseItem.values.firstWhereOrNull((e) => e.platformProductId == product.id);
if (item == null) {
continue;
}
priceMap[item] = product.price;
}
return state.copyWith(
prices: priceMap,
);
}
}
/// Handles the update information triggered by the purchase flow of the platform.
class _HandlePurchaseUpdate extends AsyncReduxAction<PurchaseService, PurchaseState> {
final PurchaseDetails purchase;
_HandlePurchaseUpdate(this.purchase);
@override
bool get trackOrigin => false;
@override
Future<PurchaseState> reduce() async {
if (purchase.status == PurchaseStatus.pending) {
return state.copyWith(pending: true);
} else {
dispatch(_SetPendingAction(false));
}
if (purchase.status == PurchaseStatus.error) {
// ignore: avoid_print
throw 'Error purchasing: ${purchase.error?.message}';
} else if (purchase.status == PurchaseStatus.purchased || purchase.status == PurchaseStatus.restored) {
final purchaseEnum = PurchaseItem.values.firstWhereOrNull((element) => element.platformProductId == purchase.productID);
if (purchaseEnum == null) {
throw 'Unknown product ID: ${purchase.productID}';
}
dispatch(AddPurchaseAction(purchaseEnum, purchase));
}
if (purchase.pendingCompletePurchase) {
// No need to verify. It's just a donation...
await InAppPurchase.instance.completePurchase(purchase);
}
return state;
}
@override
String get debugLabel => 'HandlePurchaseUpdate(${purchase.status}, ${purchase.productID})';
}
class AddPurchaseAction extends ReduxAction<PurchaseService, PurchaseState> {
final PurchaseItem item;
final PurchaseDetails purchase;
AddPurchaseAction(this.item, this.purchase);
@override
PurchaseState reduce() {
return state.copyWith(
purchases: {
...state.purchases,
item,
},
);
}
}
class _SetPendingAction extends ReduxAction<PurchaseService, PurchaseState> {
final bool pending;
_SetPendingAction(this.pending);
@override
PurchaseState reduce() => state.copyWith(pending: pending);
}
/// Action to restore purchases.
/// Dispatched on first app start or manually by the user.
class PurchaseRestoreAction extends AsyncReduxAction<PurchaseService, PurchaseState> {
@override
Future<PurchaseState> reduce() async {
try {
await InAppPurchase.instance.restorePurchases();
} catch (_) {}
return state;
}
}
/// Action to reset the purchase state.
/// Only used for testing.
class PurchaseResetAction extends ReduxAction<PurchaseService, PurchaseState> {
@override
PurchaseState reduce() => state.copyWith(
purchases: {},
pending: false,
);
}
/// Initiate the purchase flow for a product.
/// The actual callbacks are handled by [_HandlePurchaseUpdate].
class PurchaseAction extends AsyncReduxAction<PurchaseService, PurchaseState> {
final PurchaseItem item;
PurchaseAction(this.item);
@override
Future<PurchaseState> reduce() async {
final response = await InAppPurchase.instance.queryProductDetails(<String>{item.platformProductId});
final productDetails = response.productDetails.firstOrNull;
if (productDetails == null) {
throw Exception('Product not found: ${item.platformProductId}');
}
// TODO: Handle changing subscriptions if subscriptions would be added
await InAppPurchase.instance.buyNonConsumable(
purchaseParam: PurchaseParam(productDetails: productDetails),
);
return state;
}
@override
String get debugLabel => 'BuyAction(${item.name})';
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/persistence_provider.dart | import 'dart:convert';
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:common/common.dart';
import 'package:flutter/material.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/persistence/color_mode.dart';
import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:localsend_app/model/persistence/receive_history_entry.dart';
import 'package:localsend_app/model/send_mode.dart';
import 'package:localsend_app/provider/window_dimensions_provider.dart';
import 'package:localsend_app/util/alias_generator.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/security_helper.dart';
import 'package:localsend_app/util/shared_preferences_portable.dart';
import 'package:localsend_app/util/ui/dynamic_colors.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart' as path;
import 'package:refena_flutter/refena_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart';
import 'package:uuid/uuid.dart';
final _logger = Logger('PersistenceService');
// Version of the storage
const _version = 'ls_version';
// Security keys (generated on first app start)
const _securityContext = 'ls_security_context';
// Received file history
const _receiveHistory = 'ls_receive_history';
// Favorites
const _favorites = 'ls_favorites';
// App Window Offset and Size info
const _windowOffsetX = 'ls_window_offset_x';
const _windowOffsetY = 'ls_window_offset_y';
const _windowWidth = 'ls_window_width';
const _windowHeight = 'ls_window_height';
const _saveWindowPlacement = 'ls_save_window_placement';
// Settings
const _showToken = 'ls_show_token';
const _aliasKey = 'ls_alias';
const _themeKey = 'ls_theme'; // now called brightness
const _colorKey = 'ls_color';
const _localeKey = 'ls_locale';
const _portKey = 'ls_port';
const _multicastGroupKey = 'ls_multicast_group';
const _destinationKey = 'ls_destination';
const _saveToGallery = 'ls_save_to_gallery';
const _saveToHistory = 'ls_save_to_history';
const _quickSave = 'ls_quick_save';
const _autoFinish = 'ls_auto_finish';
const _minimizeToTray = 'ls_minimize_to_tray';
const _launchAtStartup = 'ls_launch_at_startup';
const _autoStartLaunchMinimized = 'ls_auto_start_launch_minimized';
const _https = 'ls_https';
const _sendMode = 'ls_send_mode';
const _enableAnimations = 'ls_enable_animations';
const _deviceType = 'ls_device_type';
const _deviceModel = 'ls_device_model';
const _shareViaLinkAutoAccept = 'ls_share_via_link_auto_accept';
final persistenceProvider = Provider<PersistenceService>((ref) {
throw Exception('persistenceProvider not initialized');
});
/// This service abstracts the persistence layer.
class PersistenceService {
final SharedPreferences _prefs;
PersistenceService._(this._prefs);
static Future<PersistenceService> initialize(DynamicColors? dynamicColors) async {
SharedPreferences prefs;
if (checkPlatform([TargetPlatform.windows]) && SharedPreferencesPortable.exists()) {
_logger.info('Using portable settings.');
SharedPreferencesStorePlatform.instance = SharedPreferencesPortable();
}
try {
prefs = await SharedPreferences.getInstance();
} catch (e) {
if (checkPlatform([TargetPlatform.windows])) {
_logger.info('Could not initialize SharedPreferences, trying to delete corrupted settings file');
final settingsDir = await path.getApplicationSupportDirectory();
final prefsFile = p.join(settingsDir.path, 'shared_preferences.json');
File(prefsFile).deleteSync();
prefs = await SharedPreferences.getInstance();
} else {
throw Exception('Could not initialize SharedPreferences');
}
}
// Locale configuration upon persistence initialisation to prevent unlocalised Alias generation
final persistedLocale = prefs.getString(_localeKey);
if (persistedLocale == null) {
LocaleSettings.useDeviceLocale();
} else {
LocaleSettings.setLocaleRaw(persistedLocale);
}
if (prefs.getInt(_version) == null) {
await prefs.setInt(_version, 1);
}
if (prefs.getString(_showToken) == null) {
await prefs.setString(_showToken, const Uuid().v4());
}
if (prefs.getString(_aliasKey) == null) {
await prefs.setString(_aliasKey, generateRandomAlias());
}
if (prefs.getString(_securityContext) == null) {
await prefs.setString(_securityContext, jsonEncode(generateSecurityContext()));
}
final supportsDynamicColors = dynamicColors != null;
if (prefs.getString(_colorKey) == null) {
await _initColorSetting(prefs, supportsDynamicColors);
} else {
// fix when device does not support dynamic colors
final supported = supportsDynamicColors ? ColorMode.values : ColorMode.values.where((e) => e != ColorMode.system);
final colorMode = supported.firstWhereOrNull((color) => color.name == prefs.getString(_colorKey));
if (colorMode == null) {
await _initColorSetting(prefs, supportsDynamicColors);
}
}
return PersistenceService._(prefs);
}
static Future<void> _initColorSetting(SharedPreferences prefs, bool supportsDynamicColors) async {
await prefs.setString(
_colorKey, checkPlatform([TargetPlatform.android]) && supportsDynamicColors ? ColorMode.system.name : ColorMode.localsend.name);
}
StoredSecurityContext getSecurityContext() {
final contextRaw = _prefs.getString(_securityContext)!;
return StoredSecurityContext.fromJson(jsonDecode(contextRaw));
}
Future<void> setSecurityContext(StoredSecurityContext context) async {
await _prefs.setString(_securityContext, jsonEncode(context));
}
List<ReceiveHistoryEntry> getReceiveHistory() {
final historyRaw = _prefs.getStringList(_receiveHistory) ?? [];
return historyRaw.map((entry) => ReceiveHistoryEntry.fromJson(jsonDecode(entry))).toList();
}
Future<void> setReceiveHistory(List<ReceiveHistoryEntry> entries) async {
final historyRaw = entries.map((entry) => jsonEncode(entry.toJson())).toList();
await _prefs.setStringList(_receiveHistory, historyRaw);
}
List<FavoriteDevice> getFavorites() {
final favoritesRaw = _prefs.getStringList(_favorites) ?? [];
return favoritesRaw.map((entry) => FavoriteDevice.fromJson(jsonDecode(entry))).toList();
}
Future<void> setFavorites(List<FavoriteDevice> entries) async {
final favoritesRaw = entries.map((entry) => jsonEncode(entry.toJson())).toList();
await _prefs.setStringList(_favorites, favoritesRaw);
}
String getShowToken() {
return _prefs.getString(_showToken)!;
}
String getAlias() {
return _prefs.getString(_aliasKey) ?? generateRandomAlias();
}
Future<void> setAlias(String alias) async {
await _prefs.setString(_aliasKey, alias);
}
ThemeMode getTheme() {
final value = _prefs.getString(_themeKey);
if (value == null) {
return ThemeMode.system;
}
return ThemeMode.values.firstWhereOrNull((theme) => theme.name == value) ?? ThemeMode.system;
}
Future<void> setTheme(ThemeMode theme) async {
await _prefs.setString(_themeKey, theme.name);
}
ColorMode getColorMode() {
final value = _prefs.getString(_colorKey);
if (value == null) {
return ColorMode.system;
}
return ColorMode.values.firstWhereOrNull((color) => color.name == value) ?? ColorMode.system;
}
Future<void> setColorMode(ColorMode color) async {
await _prefs.setString(_colorKey, color.name);
}
AppLocale? getLocale() {
final value = _prefs.getString(_localeKey);
if (value == null) {
return null;
}
return AppLocale.values.firstWhereOrNull((locale) => locale.languageTag == value);
}
Future<void> setLocale(AppLocale? locale) async {
if (locale == null) {
await _prefs.remove(_localeKey);
} else {
await _prefs.setString(_localeKey, locale.languageTag);
}
}
int getPort() {
return _prefs.getInt(_portKey) ?? defaultPort;
}
Future<void> setPort(int port) async {
await _prefs.setInt(_portKey, port);
}
bool getShareViaLinkAutoAccept() {
return _prefs.getBool(_shareViaLinkAutoAccept) ?? false;
}
Future<void> setShareViaLinkAutoAccept(bool shareViaLinkAutoAccept) async {
await _prefs.setBool(_shareViaLinkAutoAccept, shareViaLinkAutoAccept);
}
String getMulticastGroup() {
return _prefs.getString(_multicastGroupKey) ?? defaultMulticastGroup;
}
Future<void> setMulticastGroup(String group) async {
await _prefs.setString(_multicastGroupKey, group);
}
String? getDestination() {
return _prefs.getString(_destinationKey);
}
Future<void> setDestination(String? destination) async {
if (destination == null) {
await _prefs.remove(_destinationKey);
} else {
await _prefs.setString(_destinationKey, destination);
}
}
bool isSaveToGallery() {
return _prefs.getBool(_saveToGallery) ?? true;
}
Future<void> setSaveToGallery(bool saveToGallery) async {
await _prefs.setBool(_saveToGallery, saveToGallery);
}
bool isSaveToHistory() {
return _prefs.getBool(_saveToHistory) ?? true;
}
Future<void> setSaveToHistory(bool saveToHistory) async {
await _prefs.setBool(_saveToHistory, saveToHistory);
}
bool isQuickSave() {
return _prefs.getBool(_quickSave) ?? false;
}
Future<void> setQuickSave(bool quickSave) async {
await _prefs.setBool(_quickSave, quickSave);
}
bool isAutoFinish() {
return _prefs.getBool(_autoFinish) ?? false;
}
Future<void> setAutoFinish(bool autoFinish) async {
await _prefs.setBool(_autoFinish, autoFinish);
}
bool isMinimizeToTray() {
return _prefs.getBool(_minimizeToTray) ?? false;
}
Future<void> setMinimizeToTray(bool minimizeToTray) async {
await _prefs.setBool(_minimizeToTray, minimizeToTray);
}
bool isLaunchAtStartup() {
return _prefs.getBool(_launchAtStartup) ?? false;
}
Future<void> setLaunchAtStartup(bool launchAtStartup) async {
await _prefs.setBool(_launchAtStartup, launchAtStartup);
}
bool isAutoStartLaunchMinimized() {
return _prefs.getBool(_autoStartLaunchMinimized) ?? true;
}
Future<void> setAutoStartLaunchMinimized(bool launchMinimized) async {
await _prefs.setBool(_autoStartLaunchMinimized, launchMinimized);
}
bool isHttps() {
return _prefs.getBool(_https) ?? true;
}
Future<void> setHttps(bool https) async {
await _prefs.setBool(_https, https);
}
SendMode getSendMode() {
return SendMode.values.firstWhereOrNull((m) => m.name == _prefs.getString(_sendMode)) ?? SendMode.single;
}
Future<void> setSendMode(SendMode mode) async {
await _prefs.setString(_sendMode, mode.name);
}
Future<void> setWindowOffsetX(double x) async {
await _prefs.setDouble(_windowOffsetX, x);
}
Future<void> setWindowOffsetY(double y) async {
await _prefs.setDouble(_windowOffsetY, y);
}
Future<void> setWindowHeight(double height) async {
await _prefs.setDouble(_windowHeight, height);
}
Future<void> setWindowWidth(double width) async {
await _prefs.setDouble(_windowWidth, width);
}
WindowDimensions getWindowLastDimensions() {
Size? size;
Offset? position;
final offsetX = _prefs.getDouble(_windowOffsetX);
final offsetY = _prefs.getDouble(_windowOffsetY);
final width = _prefs.getDouble(_windowWidth);
final height = _prefs.getDouble(_windowHeight);
if (width != null && height != null) size = Size(width, height);
if (offsetX != null && offsetY != null) position = Offset(offsetX, offsetY);
final dimensions = {'size': size, 'position': position};
return dimensions;
}
Future<void> setSaveWindowPlacement(bool savePlacement) async {
await _prefs.setBool(_saveWindowPlacement, savePlacement);
}
bool getSaveWindowPlacement() {
if (!checkPlatformIsNotWaylandDesktop()) return false;
return _prefs.getBool(_saveWindowPlacement) ?? true;
}
Future<void> setEnableAnimations(bool enableAnimations) async {
await _prefs.setBool(_enableAnimations, enableAnimations);
}
bool getEnableAnimations() {
return _prefs.getBool(_enableAnimations) ?? true;
}
DeviceType? getDeviceType() {
return DeviceType.values.firstWhereOrNull((m) => m.name == _prefs.getString(_deviceType));
}
Future<void> setDeviceType(DeviceType deviceType) async {
await _prefs.setString(_deviceType, deviceType.name);
}
String? getDeviceModel() {
return _prefs.getString(_deviceModel);
}
Future<void> setDeviceModel(String deviceModel) async {
await _prefs.setString(_deviceModel, deviceModel);
}
Future<void> clear() async {
await _prefs.clear();
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/security_provider.dart | import 'package:common/common.dart';
import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:localsend_app/util/security_helper.dart';
import 'package:refena_flutter/refena_flutter.dart';
/// This provider manages the [StoredSecurityContext].
/// It contains all the security related data for HTTPS communication.
final securityProvider = ReduxProvider<SecurityService, StoredSecurityContext>((ref) {
return SecurityService(ref.read(persistenceProvider));
});
class SecurityService extends ReduxNotifier<StoredSecurityContext> {
final PersistenceService _persistence;
SecurityService(this._persistence);
@override
StoredSecurityContext init() {
return _persistence.getSecurityContext();
}
}
/// Generates a new [StoredSecurityContext] and persists it.
class ResetSecurityContextAction extends AsyncReduxAction<SecurityService, StoredSecurityContext> {
@override
Future<StoredSecurityContext> reduce() async {
final securityContext = generateSecurityContext();
await notifier._persistence.setSecurityContext(securityContext);
return securityContext;
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/last_devices.provider.dart | import 'package:common/common.dart';
import 'package:refena_flutter/refena_flutter.dart';
/// This provider stores the last devices that the user sent a file to.
/// It stores only the last 5 devices that were selected by be [AddressInputDialog].
/// The information is **not** persisted.
final lastDevicesProvider = ReduxProvider<LastDevicesService, List<Device>>((ref) {
return LastDevicesService();
});
class LastDevicesService extends ReduxNotifier<List<Device>> {
@override
List<Device> init() => [];
}
/// Adds a device to the list of last devices.
class AddLastDeviceAction extends ReduxAction<LastDevicesService, List<Device>> {
final Device device;
AddLastDeviceAction(this.device);
@override
List<Device> reduce() {
return {
device,
...state,
}.take(5).toList();
}
}
| 0 |
mirrored_repositories/localsend/app/lib | mirrored_repositories/localsend/app/lib/provider/dio_provider.dart | import 'dart:io';
import 'package:common/common.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:localsend_app/provider/logging/http_logs_provider.dart';
import 'package:localsend_app/provider/security_provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
class DioCollection {
final Dio startupCheckAnotherInstance;
final Dio discovery;
final Dio longLiving;
DioCollection({
required this.startupCheckAnotherInstance,
required this.discovery,
required this.longLiving,
});
}
/// Provides a dio having a specific timeout.
final dioProvider = ViewProvider((ref) {
final securityContext = ref.watch(securityProvider);
return DioCollection(
startupCheckAnotherInstance: createDio(const Duration(milliseconds: 100), securityContext, null),
discovery: createDio(const Duration(seconds: 2), securityContext, null),
longLiving: createDio(const Duration(days: 30), securityContext, ref),
);
});
/// It always trust the self signed certificate as all requests happen in a local network.
/// The user only needs to trust the local IP address.
/// Thanks to TCP (HTTP uses TCP), IP spoofing is nearly impossible.
Dio createDio(Duration timeout, StoredSecurityContext securityContext, [Ref? ref]) {
final dio = Dio(
BaseOptions(
connectTimeout: timeout,
sendTimeout: timeout,
),
);
// Allow any self signed certificate
dio.httpClientAdapter = IOHttpClientAdapter(
createHttpClient: () {
final client = HttpClient(
context: SecurityContext()
..usePrivateKeyBytes(securityContext.privateKey.codeUnits)
..useCertificateChainBytes(securityContext.certificate.codeUnits),
);
client.badCertificateCallback = (cert, host, port) => true;
return client;
},
);
// Add logging
if (ref != null) {
dio.interceptors.add(LogInterceptor(
requestHeader: false,
requestBody: true,
request: false,
responseHeader: false,
responseBody: true,
error: true,
logPrint: (log) {
ref.notifier(httpLogsProvider).addLog(log.toString());
},
));
}
return dio;
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/network/multicast_provider.dart | import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:common/common.dart';
import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/provider/dio_provider.dart';
import 'package:localsend_app/provider/logging/discovery_logs_provider.dart';
import 'package:localsend_app/provider/network/server/server_provider.dart';
import 'package:localsend_app/provider/security_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:localsend_app/util/native/device_info_helper.dart';
import 'package:localsend_app/util/sleep.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _logger = Logger('Multicast');
final multicastProvider = ViewProvider((ref) {
final deviceInfo = ref.watch(deviceInfoProvider);
return MulticastService(ref, deviceInfo);
});
class MulticastService {
final Ref _ref;
final DeviceInfoResult _deviceInfo;
bool _listening = false;
MulticastService(this._ref, this._deviceInfo);
/// Binds the UDP port and listen to UDP multicast packages
/// It will automatically answer announcement messages
Stream<Device> startListener() async* {
if (_listening) {
_logger.info('Already listening to multicast');
return;
}
_listening = true;
final streamController = StreamController<Device>();
final settings = _ref.read(settingsProvider);
final fingerprint = _ref.read(securityProvider).certificateHash;
final sockets = await _getSockets(settings.multicastGroup, settings.port);
for (final socket in sockets) {
socket.socket.listen((_) {
final datagram = socket.socket.receive();
if (datagram == null) {
return;
}
try {
final dto = MulticastDto.fromJson(jsonDecode(utf8.decode(datagram.data)));
if (dto.fingerprint == fingerprint) {
return;
}
final ip = datagram.address.address;
final peer = dto.toDevice(ip, settings.port, settings.https);
streamController.add(peer);
if ((dto.announcement == true || dto.announce == true) && _ref.read(serverProvider) != null) {
// only respond when server is running
_answerAnnouncement(peer);
}
} catch (e) {
_ref.notifier(discoveryLoggerProvider).addLog(e.toString());
}
});
_ref.notifier(discoveryLoggerProvider).addLog(
'Bind UDP multicast port (ip: ${socket.interface.addresses.map((a) => a.address).toList()}, group: ${settings.multicastGroup}, port: ${settings.port})',
);
}
// Tell everyone in the network that I am online
unawaited(
sendAnnouncement(),
);
yield* streamController.stream;
}
/// Sends an announcement which triggers a response on every LocalSend member of the network.
Future<void> sendAnnouncement() async {
final settings = _ref.read(settingsProvider);
final sockets = await _getSockets(settings.multicastGroup);
final dto = _getMulticastDto(announcement: true);
for (final wait in [100, 500, 2000]) {
await sleepAsync(wait);
_ref.notifier(discoveryLoggerProvider).addLog('[ANNOUNCE/UDP]');
for (final socket in sockets) {
try {
socket.socket.send(dto, InternetAddress(settings.multicastGroup), settings.port);
socket.socket.close();
} catch (e) {
_ref.notifier(discoveryLoggerProvider).addLog(e.toString());
}
}
}
}
/// Responds to an announcement.
Future<void> _answerAnnouncement(Device peer) async {
final settings = _ref.read(settingsProvider);
try {
// Answer with TCP
await _ref.read(dioProvider).discovery.post(
ApiRoute.register.target(peer),
data: _getRegisterDto().toJson(),
);
_ref.notifier(discoveryLoggerProvider).addLog('[RESPONSE/TCP] Announcement of ${peer.alias} (${peer.ip}, model: ${peer.deviceModel}) via TCP');
} catch (e) {
// Fallback: Answer with UDP
final sockets = await _getSockets(settings.multicastGroup);
final dto = _getMulticastDto(announcement: false);
for (final socket in sockets) {
try {
socket.socket.send(dto, InternetAddress(settings.multicastGroup), settings.port);
socket.socket.close();
} catch (e) {
_ref.notifier(discoveryLoggerProvider).addLog(e.toString());
}
}
_ref
.notifier(discoveryLoggerProvider)
.addLog('[RESPONSE/UDP] Announcement of ${peer.alias} (${peer.ip}, model: ${peer.deviceModel}) with UDP because TCP failed');
}
}
/// Returns the MulticastDto of this device in bytes.
List<int> _getMulticastDto({required bool announcement}) {
final settings = _ref.read(settingsProvider);
final serverState = _ref.read(serverProvider);
final fingerprint = _ref.read(securityProvider).certificateHash;
final dto = MulticastDto(
alias: serverState?.alias ?? settings.alias,
version: protocolVersion,
deviceModel: _deviceInfo.deviceModel,
deviceType: _deviceInfo.deviceType,
fingerprint: fingerprint,
port: serverState?.port ?? settings.port,
protocol: (serverState?.https ?? settings.https) ? ProtocolType.https : ProtocolType.http,
download: serverState?.webSendState != null,
announcement: announcement,
announce: announcement,
);
return utf8.encode(jsonEncode(dto.toJson()));
}
RegisterDto _getRegisterDto() {
final settings = _ref.read(settingsProvider);
final serverState = _ref.read(serverProvider);
final fingerprint = _ref.read(securityProvider).certificateHash;
return RegisterDto(
alias: serverState?.alias ?? settings.alias,
version: protocolVersion,
deviceModel: _deviceInfo.deviceModel,
deviceType: _deviceInfo.deviceType,
fingerprint: fingerprint,
port: serverState?.port ?? settings.port,
protocol: (serverState?.https ?? settings.https) ? ProtocolType.https : ProtocolType.http,
download: serverState?.webSendState != null,
);
}
}
class _SocketResult {
final NetworkInterface interface;
final RawDatagramSocket socket;
_SocketResult(this.interface, this.socket);
}
Future<List<_SocketResult>> _getSockets(String multicastGroup, [int? port]) async {
final interfaces = await NetworkInterface.list();
final sockets = <_SocketResult>[];
for (final interface in interfaces) {
try {
final socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, port ?? 0);
socket.joinMulticast(InternetAddress(multicastGroup), interface);
sockets.add(_SocketResult(interface, socket));
} catch (e) {
_logger.warning(
'Could not bind UDP multicast port (ip: ${interface.addresses.map((a) => a.address).toList()}, group: $multicastGroup, port: $port)',
e,
);
}
}
return sockets;
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/network/scan_facade.dart | import 'dart:async';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:localsend_app/provider/local_ip_provider.dart';
import 'package:localsend_app/provider/network/nearby_devices_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/sleep.dart';
import 'package:refena_flutter/refena_flutter.dart';
/// Scans the network via multicast first,
/// if no devices has been found, try http-based discovery on the first subnet.
/// If [forceLegacy] is true, then the http-based discovery runs in parallel.
/// Otherwise, it runs after a delay of 1 second and only if no devices has been found.
class StartSmartScan extends AsyncGlobalAction {
/// Maximum number of interfaces to scan.
/// If there are more interfaces, the first ones will be used or the user needs to select one.
static const maxInterfaces = 3;
final bool forceLegacy;
StartSmartScan({required this.forceLegacy});
@override
Future<void> reduce() async {
// Try performant Multicast/UDP method first
ref.redux(nearbyDevicesProvider).dispatch(StartMulticastScan());
// At the same time, try to discover favorites
final favorites = ref.read(favoritesProvider);
final https = ref.read(settingsProvider).https;
await ref.redux(nearbyDevicesProvider).dispatchAsync(StartFavoriteScan(devices: favorites, https: https));
if (!forceLegacy) {
// Wait a bit before trying the legacy method.
// Skip waiting if [forceLegacy] is true.
await sleepAsync(1000);
}
// If no devices has been found, then switch to legacy discovery mode
// which is purely HTTP/TCP based.
if (forceLegacy || ref.read(nearbyDevicesProvider).devices.isEmpty) {
final networkInterfaces = ref.read(localIpProvider).localIps.take(maxInterfaces).toList();
if (networkInterfaces.isNotEmpty) {
await dispatchAsync(StartLegacySubnetScan(subnets: networkInterfaces));
}
}
}
}
/// HTTP based discovery on a fixed set of subnets.
class StartLegacySubnetScan extends AsyncGlobalAction {
final List<String> subnets;
StartLegacySubnetScan({
required this.subnets,
});
@override
Future<void> reduce() async {
final settings = ref.read(settingsProvider);
final port = settings.port;
final https = settings.https;
// send announcement in parallel
ref.redux(nearbyDevicesProvider).dispatch(StartMulticastScan());
await Future.wait<void>([
for (final subnet in subnets) ref.redux(nearbyDevicesProvider).dispatchAsync(StartLegacyScan(port: port, localIp: subnet, https: https)),
]);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/network/targeted_discovery_provider.dart | import 'package:common/common.dart';
import 'package:dio/dio.dart';
import 'package:localsend_app/provider/dio_provider.dart';
import 'package:localsend_app/provider/security_provider.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _logger = Logger('TargetedDiscovery');
final targetedDiscoveryProvider = ViewProvider((ref) {
final dio = ref.watch(dioProvider).discovery;
final fingerprint = ref.watch(securityProvider).certificateHash;
return TargetedDiscoveryService(dio, fingerprint);
});
/// Try to discover a single device using the given IP and port.
class TargetedDiscoveryService {
final Dio _dio;
final String _fingerprint;
TargetedDiscoveryService(this._dio, this._fingerprint);
Future<Device?> discover({
required String ip,
required int port,
required bool https,
void Function(String url, Object? error)? onError = defaultErrorPrinter,
}) async {
// We use the legacy route to make it less breaking for older versions
final url = ApiRoute.info.targetRaw(ip, port, https, peerProtocolVersion);
try {
final response = await _dio.get(url, queryParameters: {
'fingerprint': _fingerprint,
});
final dto = InfoDto.fromJson(response.data);
return dto.toDevice(ip, port, https);
} on DioException catch (e) {
onError?.call(url, e.error);
return null;
} catch (e) {
onError?.call(url, e);
return null;
}
}
static void defaultErrorPrinter(String url, Object? error) {
_logger.warning('$url: $error');
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/network/send_provider.dart | import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:common/common.dart';
import 'package:dio/dio.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/model/send_mode.dart';
import 'package:localsend_app/model/state/send/send_session_state.dart';
import 'package:localsend_app/model/state/send/sending_file.dart';
import 'package:localsend_app/pages/home_page.dart';
import 'package:localsend_app/pages/progress_page.dart';
import 'package:localsend_app/pages/send_page.dart';
import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/provider/dio_provider.dart';
import 'package:localsend_app/provider/progress_provider.dart';
import 'package:localsend_app/provider/selection/selected_sending_files_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:routerino/routerino.dart';
import 'package:uuid/uuid.dart';
const _uuid = Uuid();
final _logger = Logger('Send');
/// This provider manages sending files to other devices.
///
/// In contrast to [serverProvider], this provider does not manage a server.
/// Instead, it only does HTTP requests to other servers.
final sendProvider = NotifierProvider<SendNotifier, Map<String, SendSessionState>>((ref) {
return SendNotifier();
});
class SendNotifier extends Notifier<Map<String, SendSessionState>> {
SendNotifier();
@override
Map<String, SendSessionState> init() {
return {};
}
/// Starts a session.
/// If [background] is true, then the session closes itself on success and no pages will be open
/// If [background] is false, then this method will open pages by itself and waits for user input to close the session.
Future<void> startSession({
required Device target,
required List<CrossFile> files,
required bool background,
}) async {
final requestDio = ref.read(dioProvider).longLiving;
final uploadDio = ref.read(dioProvider).longLiving;
final cancelToken = CancelToken();
final sessionId = _uuid.v4();
final requestState = SendSessionState(
sessionId: sessionId,
remoteSessionId: null,
background: background,
status: SessionStatus.waiting,
target: target,
files: Map.fromEntries(await Future.wait(files.map((file) async {
final id = _uuid.v4();
return MapEntry(
id,
SendingFile(
file: FileDto(
id: id,
fileName: file.name,
size: file.size,
fileType: file.fileType,
hash: null,
preview: files.length == 1 && files.first.fileType == FileType.text && files.first.bytes != null
? utf8.decode(files.first.bytes!) // send simple message by embedding it into the preview
: null,
legacy: target.version == '1.0',
),
status: FileStatus.queue,
token: null,
thumbnail: file.thumbnail,
asset: file.asset,
path: file.path,
bytes: file.bytes,
errorMessage: null,
),
);
}))),
startTime: null,
endTime: null,
cancelToken: cancelToken,
errorMessage: null,
);
final originDevice = ref.read(deviceFullInfoProvider);
final requestDto = PrepareUploadRequestDto(
info: InfoRegisterDto(
alias: originDevice.alias,
version: originDevice.version,
deviceModel: originDevice.deviceModel,
deviceType: originDevice.deviceType,
fingerprint: originDevice.fingerprint,
port: originDevice.port,
protocol: originDevice.https ? ProtocolType.https : ProtocolType.http,
download: originDevice.download,
),
files: {
for (final entry in requestState.files.entries) entry.key: entry.value.file,
},
);
state = state.updateSession(
sessionId: sessionId,
state: (_) => requestState,
);
if (!background) {
// ignore: use_build_context_synchronously, unawaited_futures
Routerino.context.push(
() => SendPage(showAppBar: false, closeSessionOnClose: true, sessionId: sessionId),
transition: RouterinoTransition.fade(),
);
}
final Response response;
try {
response = await requestDio.post(
ApiRoute.prepareUpload.target(target),
data: jsonEncode(requestDto), // jsonEncode for better logging
cancelToken: cancelToken,
);
} catch (e) {
if (e is DioException && e.response?.statusCode == 403) {
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.declined,
),
);
} else if (e is DioException && e.response?.statusCode == 409) {
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.recipientBusy,
),
);
} else {
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.finishedWithErrors,
errorMessage: e.humanErrorMessage,
),
);
}
return;
}
final Map<String, String> fileMap;
if (target.version == '1.0') {
fileMap = (response.data as Map).cast<String, String>();
} else {
if (response.statusCode == 204) {
// Nothing selected
// Interpret this as "Read and close"
fileMap = {};
} else {
try {
final responseDto = PrepareUploadResponseDto.fromJson(response.data);
fileMap = responseDto.files;
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
remoteSessionId: responseDto.sessionId,
),
);
} catch (e) {
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.finishedWithErrors,
errorMessage: e.humanErrorMessage,
),
);
return;
}
}
}
if (fileMap.isEmpty) {
// receiver has nothing selected
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.finished,
),
);
if (state[sessionId]?.background == false) {
// ignore: use_build_context_synchronously, unawaited_futures
Routerino.context.pushRootImmediately(() => const HomePage(initialTab: HomeTab.send, appStart: false));
}
closeSession(sessionId);
return;
}
final sendingFiles = {
for (final file in requestState.files.values)
file.file.id: fileMap.containsKey(file.file.id) ? file.copyWith(token: fileMap[file.file.id]) : file.copyWith(status: FileStatus.skipped),
};
if (state[sessionId]?.background == false) {
final background = ref.read(settingsProvider).sendMode == SendMode.multiple;
// ignore: use_build_context_synchronously, unawaited_futures
Routerino.context.pushAndRemoveUntil(
removeUntil: HomePage,
transition: RouterinoTransition.fade(),
// immediately is not possible: https://github.com/flutter/flutter/issues/121910
builder: () => ProgressPage(
showAppBar: background,
closeSessionOnClose: !background,
sessionId: sessionId,
),
);
}
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.sending,
files: sendingFiles,
),
);
await _send(sessionId, uploadDio, target, sendingFiles);
}
Future<void> _send(String sessionId, Dio dio, Device target, Map<String, SendingFile> files) async {
bool hasError = false;
final remoteSessionId = state[sessionId]!.remoteSessionId;
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(startTime: DateTime.now().millisecondsSinceEpoch),
);
for (final file in files.values) {
final token = file.token;
if (token == null) {
continue;
}
if (state[sessionId] != null && state[sessionId]!.status != SessionStatus.sending) {
break;
}
_logger.info('Sending ${file.file.fileName}');
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.withFileStatus(file.file.id, FileStatus.sending, null),
);
String? fileError;
try {
final cancelToken = CancelToken();
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(cancelToken: cancelToken),
);
final stopwatch = Stopwatch()..start();
await dio.post(
ApiRoute.upload.target(target, query: {
if (remoteSessionId != null) 'sessionId': remoteSessionId,
'fileId': file.file.id,
'token': token,
}),
options: Options(
headers: {
'Content-Length': file.file.size,
'Content-Type': file.file.lookupMime(),
},
),
data: file.path != null ? File(file.path!).openRead().asBroadcastStream() : file.bytes!,
onSendProgress: (curr, total) {
if (stopwatch.elapsedMilliseconds >= 100) {
stopwatch.reset();
ref.notifier(progressProvider).setProgress(
sessionId: sessionId,
fileId: file.file.id,
progress: curr / total,
);
}
},
cancelToken: cancelToken,
);
// set progress to 100% when successfully finished
ref.notifier(progressProvider).setProgress(
sessionId: sessionId,
fileId: file.file.id,
progress: 1,
);
} catch (e, st) {
fileError = e.humanErrorMessage;
hasError = true;
_logger.warning('Error while sending file ${file.file.fileName}', e, st);
}
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.withFileStatus(file.file.id, fileError != null ? FileStatus.failed : FileStatus.finished, fileError),
);
}
if (state[sessionId] != null && state[sessionId]!.status != SessionStatus.sending) {
_logger.info('Transfer was canceled.');
} else {
if (!hasError && state[sessionId]?.background == true) {
// close session because everything is fine and it is in background
closeSession(sessionId);
_logger.info('Transfer finished and session removed.');
} else {
// keep session alive when there are errors or currently in foreground
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: hasError ? SessionStatus.finishedWithErrors : SessionStatus.finished,
endTime: DateTime.now().millisecondsSinceEpoch,
),
);
if (hasError) {
_logger.info('Transfer finished with errors.');
} else {
_logger.info('Transfer finished successfully.');
}
}
}
}
/// Closes the send-session and sends a cancel event to the receiver.
void cancelSession(String sessionId) {
final sessionState = state[sessionId];
if (sessionState == null) {
return;
}
final remoteSessionId = sessionState.remoteSessionId;
sessionState.cancelToken?.cancel(); // cancel current request
// notify the receiver
try {
ref
.read(dioProvider)
.discovery
// ignore: discarded_futures
.post(ApiRoute.cancel.target(sessionState.target, query: remoteSessionId != null ? {'sessionId': remoteSessionId} : null));
} catch (e) {
_logger.warning('Error while canceling session', e);
}
// finally, close session locally
closeSession(sessionId);
}
void cancelSessionByReceiver(String sessionId) {
final sessionState = state[sessionId];
if (sessionState == null) {
return;
}
sessionState.cancelToken?.cancel(); // cancel current request
state = state.updateSession(
sessionId: sessionId,
state: (s) => s?.copyWith(
status: SessionStatus.canceledByReceiver,
endTime: DateTime.now().millisecondsSinceEpoch,
),
);
}
/// Closes the session
void closeSession(String sessionId) {
final sessionState = state[sessionId];
if (sessionState == null) {
return;
}
state = state.removeSession(ref, sessionId);
if (sessionState.status == SessionStatus.finished && ref.read(settingsProvider).sendMode == SendMode.single) {
// clear selected files
ref.redux(selectedSendingFilesProvider).dispatch(ClearSelectionAction());
}
}
void clearAllSessions() {
state = {};
ref.notifier(progressProvider).removeAllSessions();
}
void setBackground(String sessionId, bool background) {
state = state.updateSession(sessionId: sessionId, state: (s) => s?.copyWith(background: background));
}
}
extension on Map<String, SendSessionState> {
Map<String, SendSessionState> updateSession({
required String sessionId,
required SendSessionState? Function(SendSessionState? old) state,
}) {
final newState = state(this[sessionId]);
if (newState == null) {
// no change
return this;
}
return {
...this,
sessionId: newState,
};
}
Map<String, SendSessionState> removeSession(Ref ref, String sessionId) {
ref.notifier(progressProvider).removeSession(sessionId);
return {...this}..remove(sessionId);
}
}
extension on SendSessionState {
SendSessionState withFileStatus(String fileId, FileStatus status, String? errorMessage) {
return copyWith(
files: {...files}..update(
fileId,
(file) => file.copyWith(
status: status,
errorMessage: errorMessage,
),
),
);
}
}
extension on Object {
String get humanErrorMessage {
final e = this;
if (e is DioException && e.response != null) {
final body = e.response!.data;
String message;
try {
message = (body as Map)['message'];
} catch (_) {
message = body;
}
return '[${e.response!.statusCode}] $message';
}
return e.toString();
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/network/nearby_devices_provider.dart | import 'dart:async';
import 'package:collection/collection.dart';
import 'package:common/common.dart';
import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:localsend_app/model/state/nearby_devices_state.dart';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:localsend_app/provider/logging/discovery_logs_provider.dart';
import 'package:localsend_app/provider/network/multicast_provider.dart';
import 'package:localsend_app/provider/network/targeted_discovery_provider.dart';
import 'package:localsend_app/util/task_runner.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _logger = Logger('NearbyDevices');
/// This provider is responsible for:
/// - Scanning the network for other LocalSend instances
/// - Keeping track of all found devices (they are only stored in RAM)
///
/// Use [scanProvider] to have a high-level API to perform discovery operations.
final nearbyDevicesProvider = ReduxProvider<NearbyDevicesService, NearbyDevicesState>((ref) {
return NearbyDevicesService(
discoveryLogs: ref.notifier(discoveryLoggerProvider),
targetedDiscoveryService: ref.accessor(targetedDiscoveryProvider),
multicastService: ref.accessor(multicastProvider),
favoriteService: ref.notifier(favoritesProvider),
);
});
Map<String, TaskRunner> _runners = {};
class NearbyDevicesService extends ReduxNotifier<NearbyDevicesState> {
final DiscoveryLogger _discoveryLogs;
final StateAccessor<TargetedDiscoveryService> _targetedDiscoveryService;
final StateAccessor<MulticastService> _multicastService;
final FavoritesService _favoriteService;
NearbyDevicesService({
required DiscoveryLogger discoveryLogs,
required StateAccessor<TargetedDiscoveryService> targetedDiscoveryService,
required StateAccessor<MulticastService> multicastService,
required FavoritesService favoriteService,
}) : _discoveryLogs = discoveryLogs,
_targetedDiscoveryService = targetedDiscoveryService,
_multicastService = multicastService,
_favoriteService = favoriteService;
@override
NearbyDevicesState init() => const NearbyDevicesState(
runningFavoriteScan: false,
runningIps: {},
devices: {},
);
Stream<Device> _getStream(String networkInterface, int port, bool https) {
final ipList = List.generate(256, (i) => '${networkInterface.split('.').take(3).join('.')}.$i').where((ip) => ip != networkInterface).toList();
_runners[networkInterface]?.stop();
_runners[networkInterface] = TaskRunner<Device?>(
initialTasks: List.generate(
ipList.length,
(index) => () async => _doRequest(ipList[index], port, https),
),
concurrency: 50,
);
return _runners[networkInterface]!.stream.where((device) => device != null).cast<Device>();
}
Stream<Device> _getFavoriteStream({required List<FavoriteDevice> devices, required bool https}) {
final runner = TaskRunner<Device?>(
initialTasks: List.generate(
devices.length,
(index) => () async {
final device = devices[index];
return _doRequest(device.ip, device.port, https);
},
),
concurrency: 50,
);
return runner.stream.where((device) => device != null).cast<Device>();
}
Future<Device?> _doRequest(String currentIp, int port, bool https) async {
_logger.fine('Requesting $currentIp');
final device = await _targetedDiscoveryService.state.discover(
ip: currentIp,
port: port,
https: https,
onError: null,
);
if (device != null) {
_discoveryLogs.addLog('[DISCOVER/TCP] ${device.alias} (${device.ip}, model: ${device.deviceModel})');
}
return device;
}
}
/// Binds the UDP port and listens for incoming announcements.
/// This should run forever as long as the app is running.
class StartMulticastListener extends AsyncReduxAction<NearbyDevicesService, NearbyDevicesState> {
@override
Future<NearbyDevicesState> reduce() async {
await for (final device in notifier._multicastService.state.startListener()) {
await dispatchAsync(RegisterDeviceAction(device));
notifier._discoveryLogs.addLog('[DISCOVER/UDP] ${device.alias} (${device.ip}, model: ${device.deviceModel})');
}
return state;
}
}
/// Removes all found devices from the state.
class ClearFoundDevicesAction extends ReduxAction<NearbyDevicesService, NearbyDevicesState> {
@override
NearbyDevicesState reduce() {
return state.copyWith(
devices: {},
);
}
}
/// Registers a device in the state.
/// It will override any existing device with the same IP.
class RegisterDeviceAction extends AsyncReduxAction<NearbyDevicesService, NearbyDevicesState> {
final Device device;
RegisterDeviceAction(this.device);
@override
bool get trackOrigin => false;
@override
Future<NearbyDevicesState> reduce() async {
final favoriteDevice = notifier._favoriteService.state.firstWhereOrNull((e) => e.fingerprint == device.fingerprint);
if (favoriteDevice != null && !favoriteDevice.customAlias) {
// Update existing favorite with new alias
await external(notifier._favoriteService).dispatchAsync(UpdateFavoriteAction(favoriteDevice.copyWith(alias: device.alias)));
}
return state.copyWith(
devices: {...state.devices}..update(device.ip, (_) => device, ifAbsent: () => device),
);
}
}
/// It does not really "scan".
/// It just sends an announcement which will cause a response on every other LocalSend member of the network.
class StartMulticastScan extends ReduxAction<NearbyDevicesService, NearbyDevicesState> {
@override
NearbyDevicesState reduce() {
notifier._multicastService.state.sendAnnouncement(); // ignore: discarded_futures
return state;
}
}
/// Scans one particular subnet with traditional HTTP/TCP discovery.
/// This method awaits until the scan is finished.
class StartLegacyScan extends AsyncReduxAction<NearbyDevicesService, NearbyDevicesState> {
final int port;
final String localIp;
final bool https;
StartLegacyScan({
required this.port,
required this.localIp,
required this.https,
});
@override
Future<NearbyDevicesState> reduce() async {
if (state.runningIps.contains(localIp)) {
// already running for the same localIp
return state;
}
dispatch(_SetRunningIpsAction({...state.runningIps, localIp}));
await for (final device in notifier._getStream(localIp, port, https)) {
await dispatchAsync(RegisterDeviceAction(device));
}
return state.copyWith(
runningIps: state.runningIps.where((ip) => ip != localIp).toSet(),
);
}
}
class StartFavoriteScan extends AsyncReduxAction<NearbyDevicesService, NearbyDevicesState> {
final List<FavoriteDevice> devices;
final bool https;
StartFavoriteScan({
required this.devices,
required this.https,
});
@override
Future<NearbyDevicesState> reduce() async {
if (devices.isEmpty) {
return state;
}
dispatch(_SetRunningFavoriteScanAction(true));
await for (final device in notifier._getFavoriteStream(devices: devices, https: https)) {
await dispatchAsync(RegisterDeviceAction(device));
}
return state.copyWith(
runningFavoriteScan: false,
);
}
}
class _SetRunningIpsAction extends ReduxAction<NearbyDevicesService, NearbyDevicesState> {
final Set<String> runningIps;
_SetRunningIpsAction(this.runningIps);
@override
NearbyDevicesState reduce() {
return state.copyWith(
runningIps: runningIps,
);
}
}
class _SetRunningFavoriteScanAction extends ReduxAction<NearbyDevicesService, NearbyDevicesState> {
final bool running;
_SetRunningFavoriteScanAction(this.running);
@override
NearbyDevicesState reduce() {
return state.copyWith(
runningFavoriteScan: running,
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider/network | mirrored_repositories/localsend/app/lib/provider/network/server/server_utils.dart | import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart' show rootBundle;
import 'package:localsend_app/model/state/server/server_state.dart';
import 'package:localsend_app/util/user_agent_analyzer.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:shelf/shelf.dart';
/// Having this class allows us to have one parameter to access all relevant server methods.
class ServerUtils {
/// The ref to the provider.
Ref Function() refFunc;
Ref get ref => refFunc();
/// The current server state.
/// This should be used within route controllers because it is guaranteed to be online and therefore non-null.
ServerState Function() getState;
/// The current server state or null.
/// This should be used outside of routes because the server may be offline.
ServerState? Function() getStateOrNull;
/// Updates the server state.
void Function(ServerState? Function(ServerState? oldState) builder) setState;
/// Syntax sugar for creating an API response.
///
/// Usage:
/// responseApi(200, message: 'Hello World')
Response responseJson(int code, {String? message, Map<String, dynamic>? body}) {
return Response(
code,
body: jsonEncode(message != null ? {'message': message} : (body ?? {})),
headers: {'content-type': 'application/json'},
);
}
/// Syntax sugar for creating a HTML response.
///
/// Usage:
/// responseHtml(200, 'assets/web/index.html')
Future<Response> responseAsset(int code, String asset, [String type = 'text/html; charset=utf-8']) async {
return Response(
code,
body: await rootBundle.loadString(asset),
headers: {'content-type': type},
);
}
ServerUtils({
required this.refFunc,
required this.getState,
required this.getStateOrNull,
required this.setState,
});
}
extension RequestExt on Request {
/// The IP address of the client.
String get ip {
return (context['shelf.io.connection_info'] as HttpConnectionInfo).remoteAddress.address;
}
/// Client's device info parsed from the user agent.
String get deviceInfo {
final userAgent = headers['user-agent'];
if (userAgent == null) {
return 'Unknown';
}
final userAgentAnalyzer = UserAgentAnalyzer();
final browser = userAgentAnalyzer.getBrowser(userAgent);
final os = userAgentAnalyzer.getOS(userAgent);
if (browser != null && os != null) {
return '$browser ($os)';
} else if (browser != null) {
return browser;
} else if (os != null) {
return os;
} else {
return 'Unknown';
}
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider/network | mirrored_repositories/localsend/app/lib/provider/network/server/server_provider.dart | import 'dart:async';
import 'dart:io';
import 'package:common/common.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/model/state/server/server_state.dart';
import 'package:localsend_app/provider/network/server/controller/receive_controller.dart';
import 'package:localsend_app/provider/network/server/controller/send_controller.dart';
import 'package:localsend_app/provider/network/server/server_utils.dart';
import 'package:localsend_app/provider/security_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/alias_generator.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
final _logger = Logger('Server');
/// This provider runs the server and provides the current server state.
/// It is a singleton provider, so only one server can be running at a time.
/// The server state is null if the server is not running.
/// The server can receive files (since v1) and send files (since v2).
final serverProvider = NotifierProvider<ServerService, ServerState?>((ref) {
return ServerService();
});
class ServerService extends Notifier<ServerState?> {
late final _serverUtils = ServerUtils(
refFunc: () => ref,
getState: () => state!,
getStateOrNull: () => state,
setState: (builder) => state = builder(state),
);
late final _receiveController = ReceiveController(_serverUtils);
late final _sendController = SendController(_serverUtils);
ServerService();
@override
ServerState? init() {
return null;
}
/// Starts the server from user settings.
Future<ServerState?> startServerFromSettings() async {
final settings = ref.read(settingsProvider);
return startServer(
alias: settings.alias,
port: settings.port,
https: settings.https,
);
}
/// Starts the server.
Future<ServerState?> startServer({
required String alias,
required int port,
required bool https,
}) async {
if (state != null) {
_logger.info('Server already running.');
return null;
}
alias = alias.trim();
if (alias.isEmpty) {
alias = generateRandomAlias();
}
if (port < 0 || port > 65535) {
port = defaultPort;
}
final router = Router();
final fingerprint = ref.read(securityProvider).certificateHash;
_receiveController.installRoutes(
router: router,
alias: alias,
port: port,
https: https,
fingerprint: fingerprint,
showToken: ref.read(settingsProvider).showToken,
);
_sendController.installRoutes(
router: router,
alias: alias,
fingerprint: fingerprint,
);
_logger.info('Starting server...');
ServerState? newServerState;
if (https) {
final securityContext = ref.read(securityProvider);
newServerState = ServerState(
httpServer: await _startServer(
router: router,
port: port,
securityContext: SecurityContext()
..usePrivateKeyBytes(securityContext.privateKey.codeUnits)
..useCertificateChainBytes(securityContext.certificate.codeUnits),
),
alias: alias,
port: port,
https: true,
session: null,
webSendState: null,
);
_logger.info('Server started. (Port: ${newServerState.port}, HTTPS only)');
} else {
newServerState = ServerState(
httpServer: await _startServer(
router: router,
port: port,
securityContext: null,
),
alias: alias,
port: port,
https: false,
session: null,
webSendState: null,
);
_logger.info('Server started. (Port: ${newServerState.port}, HTTP only)');
}
state = newServerState;
return newServerState;
}
Future<void> stopServer() async {
_logger.info('Stopping server...');
await state?.httpServer.close(force: true);
state = null;
_logger.info('Server stopped.');
}
Future<ServerState?> restartServerFromSettings() async {
await stopServer();
return await startServerFromSettings();
}
Future<ServerState?> restartServer({required String alias, required int port, required bool https}) async {
await stopServer();
return await startServer(alias: alias, port: port, https: https);
}
void acceptFileRequest(Map<String, String> fileNameMap) {
_receiveController.acceptFileRequest(fileNameMap);
}
void declineFileRequest() {
_receiveController.declineFileRequest();
}
/// Updates the destination directory for the current session.
void setSessionDestinationDir(String destinationDirectory) {
_receiveController.setSessionDestinationDir(destinationDirectory);
}
/// Updates the save to gallery setting for the current session.
void setSessionSaveToGallery(bool saveToGallery) {
_receiveController.setSessionSaveToGallery(saveToGallery);
}
/// In addition to [closeSession], this method also cancels incoming requests.
void cancelSession() {
_receiveController.cancelSession();
}
/// Clears the session.
void closeSession() {
_receiveController.closeSession();
}
/// Initializes the web send state.
Future<void> initializeWebSend(List<CrossFile> files) async {
await _sendController.initializeWebSend(files: files);
}
/// Updates the auto accept setting for web send.
void setWebSendAutoAccept(bool autoAccept) {
state = state?.copyWith(
webSendState: state?.webSendState?.copyWith(
autoAccept: autoAccept,
),
);
}
/// Accepts the web send request.
void acceptWebSendRequest(String sessionId) {
_sendController.acceptRequest(sessionId);
}
/// Declines the web send request.
void declineWebSendRequest(String sessionId) {
_sendController.declineRequest(sessionId);
}
}
/// Starts the (actual) server.
/// This binds the server to the given [port] and returns the [HttpServer] instance.
Future<HttpServer> _startServer({
required Router router,
required int port,
required SecurityContext? securityContext,
}) async {
return serve(
router.call,
'0.0.0.0',
port,
securityContext: securityContext,
);
}
// Below is a first prototype of mTLS (mutual TLS).
// Problem:
// - we cannot request client certificates while ignoring errors
// Future<HttpServer> _startServer({
// required Router router,
// required int port,
// required SecurityContext? securityContext,
// }) async {
// const address = '0.0.0.0';
// final server = await (securityContext == null
// ? HttpServer.bind(address, port)
// : HttpServer.bindSecure(
// address,
// port,
// securityContext,
// requestClientCertificate: true,
// ));
//
// final stream = server.map((request) {
// print('Request Cert: ${request.certificate?.pem}');
// return request;
// });
//
// serveRequests(stream, router);
// return server;
// }
| 0 |
mirrored_repositories/localsend/app/lib/provider/network/server | mirrored_repositories/localsend/app/lib/provider/network/server/controller/receive_controller.dart | import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:common/common.dart';
import 'package:flutter/foundation.dart';
import 'package:localsend_app/model/state/send/send_session_state.dart';
import 'package:localsend_app/model/state/server/receive_session_state.dart';
import 'package:localsend_app/model/state/server/receiving_file.dart';
import 'package:localsend_app/pages/home_page.dart';
import 'package:localsend_app/pages/progress_page.dart';
import 'package:localsend_app/pages/receive_page.dart';
import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/provider/dio_provider.dart';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:localsend_app/provider/logging/discovery_logs_provider.dart';
import 'package:localsend_app/provider/network/nearby_devices_provider.dart';
import 'package:localsend_app/provider/network/send_provider.dart';
import 'package:localsend_app/provider/network/server/server_utils.dart';
import 'package:localsend_app/provider/progress_provider.dart';
import 'package:localsend_app/provider/receive_history_provider.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:localsend_app/util/native/directories.dart';
import 'package:localsend_app/util/native/file_saver.dart';
import 'package:localsend_app/util/native/platform_check.dart';
import 'package:localsend_app/util/native/tray_helper.dart';
import 'package:logging/logging.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:routerino/routerino.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:uuid/uuid.dart';
import 'package:window_manager/window_manager.dart';
const _uuid = Uuid();
final _logger = Logger('ReceiveController');
/// Handles all requests for receiving files.
class ReceiveController {
final ServerUtils server;
ReceiveController(this.server);
/// Installs all routes for receiving files.
void installRoutes({
required Router router,
required String alias,
required int port,
required bool https,
required String fingerprint,
required String showToken,
}) {
router.get(ApiRoute.info.v1, (Request request) {
return _infoHandler(request: request, alias: alias, fingerprint: fingerprint);
});
router.get(ApiRoute.info.v2, (Request request) {
return _infoHandler(request: request, alias: alias, fingerprint: fingerprint);
});
// An upgraded version of /info
router.post(ApiRoute.register.v1, (Request request) async {
return _registerHandler(request: request, alias: alias, port: port, https: https, fingerprint: fingerprint);
});
router.post(ApiRoute.register.v2, (Request request) async {
return _registerHandler(request: request, alias: alias, port: port, https: https, fingerprint: fingerprint);
});
router.post(ApiRoute.prepareUpload.v1, (Request request) async {
return _prepareUploadHandler(request: request, port: port, https: https, v2: false);
});
router.post(ApiRoute.prepareUpload.v2, (Request request) async {
return _prepareUploadHandler(request: request, port: port, https: https, v2: true);
});
router.post(ApiRoute.upload.v1, (Request request) async {
return _uploadHandler(request: request, v2: false);
});
router.post(ApiRoute.upload.v2, (Request request) async {
return _uploadHandler(request: request, v2: true);
});
router.post(ApiRoute.cancel.v1, (Request request) {
return _cancelHandler(request: request, v2: false);
});
router.post(ApiRoute.cancel.v2, (Request request) {
return _cancelHandler(request: request, v2: true);
});
router.post(ApiRoute.show.v1, (Request request) async {
return _showHandler(request: request, showToken: showToken);
});
router.post(ApiRoute.show.v2, (Request request) async {
return _showHandler(request: request, showToken: showToken);
});
}
Response _infoHandler({
required Request request,
required String alias,
required String fingerprint,
}) {
final senderFingerprint = request.url.queryParameters['fingerprint'];
if (senderFingerprint == fingerprint) {
// "I talked to myself lol"
return server.responseJson(412, message: 'Self-discovered');
}
final deviceInfo = server.ref.read(deviceInfoProvider);
final dto = InfoDto(
alias: alias,
version: protocolVersion,
deviceModel: deviceInfo.deviceModel,
deviceType: deviceInfo.deviceType,
fingerprint: fingerprint,
download: server.getState().webSendState != null,
);
return server.responseJson(200, body: dto.toJson());
}
Future<Response> _registerHandler({
required Request request,
required String alias,
required String fingerprint,
required int port,
required bool https,
}) async {
final payload = await request.readAsString();
final RegisterDto requestDto;
try {
requestDto = RegisterDto.fromJson(jsonDecode(payload));
} catch (e) {
return server.responseJson(400, message: 'Request body malformed');
}
if (requestDto.fingerprint == fingerprint) {
// "I talked to myself lol"
return server.responseJson(412, message: 'Self-discovered');
}
// Save device information
await server.ref.redux(nearbyDevicesProvider).dispatchAsync(RegisterDeviceAction(requestDto.toDevice(request.ip, port, https)));
server.ref.notifier(discoveryLoggerProvider).addLog('[DISCOVER/TCP] Received "/register" HTTP request: ${requestDto.alias} (${request.ip})');
final deviceInfo = server.ref.read(deviceInfoProvider);
final responseDto = InfoDto(
alias: alias,
version: protocolVersion,
deviceModel: deviceInfo.deviceModel,
deviceType: deviceInfo.deviceType,
fingerprint: fingerprint,
download: server.getState().webSendState != null,
);
return server.responseJson(200, body: responseDto.toJson());
}
Future<Response> _prepareUploadHandler({
required Request request,
required int port,
required bool https,
required bool v2,
}) async {
if (server.getState().session != null) {
// block incoming requests when we are already in a session
return server.responseJson(409, message: 'Blocked by another session');
}
final payload = await request.readAsString();
final PrepareUploadRequestDto dto;
try {
dto = PrepareUploadRequestDto.fromJson(jsonDecode(payload));
} catch (e) {
return server.responseJson(400, message: 'Request body malformed');
}
if (dto.files.isEmpty) {
// block empty requests (at least one file is required)
return server.responseJson(400, message: 'Request must contain at least one file');
}
final settings = server.ref.read(settingsProvider);
final destinationDir = settings.destination ?? await getDefaultDestinationDirectory();
final cacheDir = await getCacheDirectory();
final sessionId = _uuid.v4();
_logger.info('Session Id: $sessionId');
_logger.info('Destination Directory: $destinationDir');
final streamController = StreamController<Map<String, String>?>();
server.setState(
(oldState) => oldState?.copyWith(
session: ReceiveSessionState(
sessionId: sessionId,
status: SessionStatus.waiting,
sender: dto.info.toDevice(request.ip, port, https),
senderAlias: server.ref.read(favoritesProvider).firstWhereOrNull((e) => e.fingerprint == dto.info.fingerprint)?.alias ?? dto.info.alias,
files: {
for (final file in dto.files.values)
file.id: ReceivingFile(
file: file,
status: FileStatus.queue,
token: null,
desiredName: null,
path: null,
savedToGallery: false,
errorMessage: null,
),
},
startTime: null,
endTime: null,
destinationDirectory: destinationDir,
cacheDirectory: cacheDir,
saveToGallery: checkPlatformWithGallery() && settings.saveToGallery && dto.files.values.every((f) => !f.fileName.contains('/')),
responseHandler: streamController,
),
),
);
final quickSave = settings.quickSave && server.getState().session?.message == null;
final Map<String, String>? selection;
if (quickSave) {
// accept all files
selection = {
for (final f in dto.files.values) f.id: f.fileName,
};
} else {
if (checkPlatformHasTray() && (await windowManager.isMinimized() || !(await windowManager.isVisible()) || !(await windowManager.isFocused()))) {
await showFromTray();
}
// ignore: use_build_context_synchronously, unawaited_futures
Routerino.context.push(() => const ReceivePage());
// Delayed response (waiting for user's decision)
selection = await streamController.stream.first;
}
if (server.getState().session == null) {
// somehow this state is already disposed
return server.responseJson(500, message: 'Server is in invalid state');
}
if (selection == null) {
closeSession();
return server.responseJson(403, message: 'File request declined by recipient');
}
if (selection.isEmpty) {
// nothing selected, send this to sender and close session
// This usually happens for message transfers
closeSession();
return server.responseJson(204);
}
server.setState(
(oldState) {
final receiveState = oldState!.session!;
return oldState.copyWith(
session: receiveState.copyWith(
status: SessionStatus.sending,
files: Map.fromEntries(
receiveState.files.values.map((entry) {
final desiredName = selection![entry.file.id];
return MapEntry(
entry.file.id,
ReceivingFile(
file: entry.file,
status: desiredName != null ? FileStatus.queue : FileStatus.skipped,
token: desiredName != null ? _uuid.v4() : null,
desiredName: desiredName,
path: null,
savedToGallery: false,
errorMessage: null,
),
);
}),
),
responseHandler: null,
),
);
},
);
if (quickSave) {
// ignore: use_build_context_synchronously, unawaited_futures
Routerino.context.pushImmediately(() => ProgressPage(
showAppBar: false,
closeSessionOnClose: true,
sessionId: sessionId,
));
}
final files = {
for (final file in server.getState().session!.files.values.where((f) => f.token != null)) file.file.id: file.token,
};
if (checkPlatform([TargetPlatform.android, TargetPlatform.iOS])) {
if (checkPlatform([TargetPlatform.android]) && !server.getState().session!.destinationDirectory.startsWith('/storage/emulated/0/Download')) {
// Android requires manageExternalStorage permission to save files outside of the Download directory
try {
final result = await Permission.manageExternalStorage.request();
_logger.info('manageExternalStorage permission: $result');
} catch (e) {
_logger.warning('Could not request manageExternalStorage permission', e);
}
}
try {
await Permission.storage.request();
} catch (e) {
_logger.warning('Could not request storage permission', e);
}
}
if (v2) {
return server.responseJson(200,
body: PrepareUploadResponseDto(
sessionId: sessionId,
files: files.cast(),
).toJson());
}
return server.responseJson(200, body: files);
}
Future<Response> _uploadHandler({
required Request request,
required bool v2,
}) async {
final receiveState = server.getState().session;
if (receiveState == null) {
return server.responseJson(409, message: 'No session');
}
if (request.ip != receiveState.sender.ip) {
_logger.warning('Invalid ip address: ${request.ip} (expected: ${receiveState.sender.ip})');
return server.responseJson(403, message: 'Invalid IP address: ${request.ip}');
}
if (receiveState.status != SessionStatus.sending) {
_logger.warning('Wrong state: ${receiveState.status} (expected: ${SessionStatus.sending})');
return server.responseJson(409, message: 'Recipient is in wrong state');
}
final fileId = request.url.queryParameters['fileId'];
final token = request.url.queryParameters['token'];
final sessionId = request.url.queryParameters['sessionId'];
if (fileId == null || token == null || (v2 && sessionId == null)) {
// reject because of missing parameters
_logger.warning('Missing parameters: fileId=$fileId, token=$token, sessionId=$sessionId');
return server.responseJson(400, message: 'Missing parameters');
}
if (v2 && sessionId != receiveState.sessionId) {
// reject because of wrong session id
_logger.warning('Wrong session id: $sessionId (expected: ${receiveState.sessionId})');
return server.responseJson(403, message: 'Invalid session id');
}
final receivingFile = receiveState.files[fileId];
if (receivingFile == null || receivingFile.token != token) {
// reject because there is no file or token does not match
_logger.warning('Wrong fileId: $fileId (expected: ${receivingFile?.file.id})');
return server.responseJson(403, message: 'Invalid token');
}
// begin of actual file transfer
server.setState(
(oldState) => oldState?.copyWith(
session: receiveState.copyWith(
files: {...receiveState.files}..update(
fileId,
(_) => receivingFile.copyWith(
status: FileStatus.sending,
token: null, // remove token to reject further uploads of the same file
),
),
startTime: receiveState.startTime ?? DateTime.now().millisecondsSinceEpoch,
),
),
);
try {
final fileType = receivingFile.file.fileType;
final saveToGallery = receiveState.saveToGallery && (fileType == FileType.image || fileType == FileType.video);
final destinationPath = await digestFilePathAndPrepareDirectory(
parentDirectory: saveToGallery ? receiveState.cacheDirectory : receiveState.destinationDirectory,
fileName: receivingFile.desiredName!,
);
_logger.info('Saving ${receivingFile.file.fileName} to $destinationPath');
await saveFile(
destinationPath: destinationPath,
name: receivingFile.desiredName!,
saveToGallery: saveToGallery,
isImage: fileType == FileType.image,
stream: request.read(),
androidSdkInt: server.ref.read(deviceInfoProvider).androidSdkInt,
onProgress: (savedBytes) {
if (receivingFile.file.size != 0) {
server.ref.notifier(progressProvider).setProgress(
sessionId: receiveState.sessionId,
fileId: fileId,
progress: savedBytes / receivingFile.file.size,
);
}
},
);
if (server.getState().session == null || server.getState().session!.status != SessionStatus.sending) {
return server.responseJson(500, message: 'Server is in invalid state');
}
server.setState(
(oldState) => oldState?.copyWith(
session: oldState.session?.fileFinished(
fileId: fileId,
status: FileStatus.finished,
path: saveToGallery ? null : destinationPath,
savedToGallery: saveToGallery,
errorMessage: null,
),
),
);
// Track it in history
await server.ref.redux(receiveHistoryProvider).dispatchAsync(AddHistoryEntryAction(
entryId: fileId,
fileName: receivingFile.desiredName!,
fileType: receivingFile.file.fileType,
path: saveToGallery ? null : destinationPath,
savedToGallery: saveToGallery,
fileSize: receivingFile.file.size,
senderAlias: receiveState.senderAlias,
timestamp: DateTime.now().toUtc(),
));
_logger.info('Saved ${receivingFile.file.fileName}.');
} catch (e, st) {
server.setState(
(oldState) => oldState?.copyWith(
session: oldState.session?.fileFinished(
fileId: fileId,
status: FileStatus.failed,
path: null,
savedToGallery: false,
errorMessage: e.toString(),
),
),
);
_logger.severe('Failed to save file', e, st);
}
server.ref.notifier(progressProvider).setProgress(
sessionId: receiveState.sessionId,
fileId: fileId,
progress: 1,
);
final session = server.getState().session!;
if (session.status == SessionStatus.sending &&
session.files.values.every((f) => f.status == FileStatus.finished || f.status == FileStatus.skipped || f.status == FileStatus.failed)) {
final hasError = session.files.values.any((f) => f.status == FileStatus.failed);
server.setState(
(oldState) => oldState?.copyWith(
session: oldState.session!.copyWith(
status: hasError ? SessionStatus.finishedWithErrors : SessionStatus.finished,
endTime: DateTime.now().millisecondsSinceEpoch,
),
),
);
if (server.ref.read(settingsProvider).quickSave && server.getState().session?.message == null) {
// close the session **after** return of the response
Future.delayed(Duration.zero, () {
closeSession();
// ignore: use_build_context_synchronously
Routerino.context.pushRootImmediately(() => const HomePage(initialTab: HomeTab.receive, appStart: false));
});
}
_logger.info('Received all files.');
}
return server.getState().session?.files[fileId]?.status == FileStatus.finished
? server.responseJson(200)
: server.responseJson(500, message: 'Could not save file');
}
Response _cancelHandler({
required Request request,
required bool v2,
}) {
final receiveSession = server.getState().session;
if (receiveSession != null) {
// We are currently receiving files.
if (!v2 && receiveSession.sender.version != '1.0') {
// disallow v1 cancel for active v2 sessions
return server.responseJson(403, message: 'No permission');
}
if (receiveSession.sender.ip != request.ip) {
return server.responseJson(403, message: 'No permission');
}
// require session id for v2
// don't require it when during waiting state
if (v2 && receiveSession.status != SessionStatus.waiting) {
final sessionId = request.url.queryParameters['sessionId'];
if (sessionId != receiveSession.sessionId) {
return server.responseJson(403, message: 'No permission');
}
}
// check if valid state
final currentStatus = receiveSession.status;
if (currentStatus != SessionStatus.waiting && currentStatus != SessionStatus.sending) {
return server.responseJson(403, message: 'No permission');
}
_cancelBySender(server);
return server.responseJson(200);
} else {
// We are not receiving files so we may be sending files.
final sessionId = request.url.queryParameters['sessionId'];
final sendSessions = server.ref.read(sendProvider);
final SendSessionState sendState;
if (v2) {
// In v2, we require sessionId.
final selectedSession = sendSessions.values.firstWhereOrNull((s) => s.remoteSessionId == sessionId);
if (selectedSession == null) {
return server.responseJson(403, message: 'No permission');
}
sendState = selectedSession;
} else {
// In v1, we are a little bit more tolerant.
// Let's assume the sessionId if only one send session exist
final onlySession = sendSessions.values.singleOrNull;
if (onlySession == null) {
return server.responseJson(403, message: 'No permission');
}
sendState = onlySession;
}
if (sendState.target.ip != request.ip) {
return server.responseJson(403, message: 'No permission');
}
// check if valid state
if (sendState.status != SessionStatus.sending) {
return server.responseJson(403, message: 'No permission');
}
server.ref.notifier(sendProvider).cancelSessionByReceiver(
sendState.sessionId,
);
return server.responseJson(200);
}
}
Response _showHandler({
required Request request,
required String showToken,
}) {
final senderToken = request.url.queryParameters['token'];
if (senderToken == showToken && checkPlatformIsDesktop()) {
// ignore: discarded_futures
showFromTray().catchError((e) {
// don't wait for it
_logger.severe('Failed to show from tray', e);
});
return server.responseJson(200);
}
return server.responseJson(403, message: 'Invalid token');
}
void acceptFileRequest(Map<String, String> fileNameMap) {
final controller = server.getState().session?.responseHandler;
if (controller == null || controller.isClosed) {
return;
}
controller.add(fileNameMap);
controller.close(); // ignore: discarded_futures
}
void declineFileRequest() {
final controller = server.getState().session?.responseHandler;
if (controller == null || controller.isClosed) {
return;
}
controller.add(null);
controller.close(); // ignore: discarded_futures
}
/// Updates the destination directory for the current session.
void setSessionDestinationDir(String destinationDirectory) {
server.setState(
(oldState) => oldState?.copyWith(
session: oldState.session?.copyWith(
destinationDirectory: destinationDirectory.replaceAll('\\', '/'),
),
),
);
}
/// Updates the "saveToGallery" setting for the current session.
void setSessionSaveToGallery(bool saveToGallery) {
server.setState(
(oldState) => oldState?.copyWith(
session: oldState.session?.copyWith(
saveToGallery: saveToGallery,
),
),
);
}
/// In addition to [closeSession], this method also
/// - cancels incoming requests (TODO)
/// - notifies the sender that the session has been canceled
void cancelSession() async {
final session = server.getStateOrNull()?.session;
if (session == null) {
// the server is not running
return;
}
// notify sender
try {
// ignore: unawaited_futures
server.ref.read(dioProvider).discovery.post(ApiRoute.cancel.target(session.sender, query: {'sessionId': session.sessionId}));
} catch (e) {
_logger.warning('Failed to notify sender', e);
}
closeSession();
// TODO: cancel incoming requests (https://github.com/dart-lang/shelf/issues/319)
// restartServer(alias: tempState.alias, port: tempState.port);
}
void closeSession() {
final sessionId = server.getStateOrNull()?.session?.sessionId;
if (sessionId == null) {
return;
}
server.setState(
(oldState) => oldState?.copyWith(
session: null,
),
);
server.ref.notifier(progressProvider).removeSession(sessionId);
}
}
void _cancelBySender(ServerUtils server) {
final receiveSession = server.getState().session;
if (receiveSession == null) {
return;
}
if (receiveSession.status == SessionStatus.waiting) {
// received cancel during accept/decline
// pop just in case if user is in [ReceiveOptionsPage]
Routerino.context.popUntil(ReceivePage);
}
server.setState((oldState) => oldState?.copyWith(
session: oldState.session?.copyWith(
status: SessionStatus.canceledBySender,
endTime: DateTime.now().millisecondsSinceEpoch,
),
));
}
extension on ReceiveSessionState {
ReceiveSessionState fileFinished({
required String fileId,
required FileStatus status,
required String? path,
required bool savedToGallery,
required String? errorMessage,
}) {
return copyWith(
files: {...files}..update(
fileId,
(file) => file.copyWith(
status: status,
path: path,
savedToGallery: savedToGallery,
errorMessage: errorMessage,
),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider/network/server | mirrored_repositories/localsend/app/lib/provider/network/server/controller/send_controller.dart | import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:common/common.dart';
import 'package:localsend_app/gen/assets.gen.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/model/state/send/web/web_send_file.dart';
import 'package:localsend_app/model/state/send/web/web_send_session.dart';
import 'package:localsend_app/model/state/send/web/web_send_state.dart';
import 'package:localsend_app/provider/device_info_provider.dart';
import 'package:localsend_app/provider/network/server/server_utils.dart';
import 'package:localsend_app/provider/settings_provider.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
import 'package:uuid/uuid.dart';
const _uuid = Uuid();
/// Handles all requests for sending files.
class SendController {
final ServerUtils server;
SendController(this.server);
/// Installs all routes for receiving files.
void installRoutes({
required Router router,
required String alias,
required String fingerprint,
}) {
router.get('/', (Request request) async {
final state = server.getState();
if (state.webSendState == null) {
// There is no web send state
return server.responseAsset(403, Assets.web.error403);
}
return server.responseAsset(200, Assets.web.index);
});
router.get('/main.js', (Request request) async {
final state = server.getState();
if (state.webSendState == null) {
// There is no web send state
return server.responseAsset(403, Assets.web.error403);
}
return server.responseAsset(200, Assets.web.main, 'text/javascript; charset=utf-8');
});
router.get('/i18n.json', (Request request) async {
final state = server.getState();
if (state.webSendState == null) {
// There is no web send state
return server.responseJson(403, message: 'Web send not initialized.');
}
return server.responseJson(200, body: {
'waiting': t.web.waiting,
'rejected': t.web.rejected,
'files': t.web.files,
'fileName': t.web.fileName,
'size': t.web.size,
});
});
router.post(ApiRoute.prepareDownload.v2, (Request request) async {
final state = server.getState();
if (state.webSendState == null) {
// There is no web send state
return server.responseJson(403, message: 'Web send not initialized.');
}
final requestSessionId = request.url.queryParameters['sessionId'];
if (requestSessionId != null) {
// Check if the user already has permission
final session = server.getState().webSendState?.sessions[requestSessionId];
if (session != null && session.responseHandler == null && session.ip == request.ip) {
final deviceInfo = server.ref.read(deviceInfoProvider);
return server.responseJson(200,
body: ReceiveRequestResponseDto(
info: InfoDto(
alias: alias,
version: protocolVersion,
deviceModel: deviceInfo.deviceModel,
deviceType: deviceInfo.deviceType,
fingerprint: fingerprint,
download: true,
),
sessionId: session.sessionId,
files: {
for (final entry in state.webSendState!.files.entries) entry.key: entry.value.file,
},
).toJson());
}
}
final streamController = StreamController<bool>();
final sessionId = request.ip;
server.setState(
(oldState) => oldState!.copyWith(
webSendState: oldState.webSendState!.copyWith(
sessions: {
...oldState.webSendState!.sessions,
sessionId: WebSendSession(
sessionId: sessionId,
responseHandler: streamController,
ip: request.ip,
deviceInfo: request.deviceInfo,
),
},
),
),
);
final accepted = state.webSendState?.autoAccept == true || await streamController.stream.first;
if (!accepted) {
// user rejected the file transfer
server.setState(
(oldState) => oldState!.copyWith(
webSendState: oldState.webSendState!.copyWith(
sessions: {
for (final entry in oldState.webSendState!.sessions.entries)
if (entry.key != sessionId) entry.key: entry.value, // remove session
},
),
),
);
return server.responseJson(403, message: 'File transfer rejected.');
}
server.setState(
(oldState) => oldState!.copyWith(
webSendState: oldState.webSendState!.updateSession(
sessionId: sessionId,
update: (oldSession) {
return oldSession.copyWith(
responseHandler: null, // this indicates that the session is active
);
},
),
),
);
final deviceInfo = server.ref.read(deviceInfoProvider);
return server.responseJson(200,
body: ReceiveRequestResponseDto(
info: InfoDto(
alias: alias,
version: protocolVersion,
deviceModel: deviceInfo.deviceModel,
deviceType: deviceInfo.deviceType,
fingerprint: fingerprint,
download: true,
),
sessionId: sessionId,
files: {
for (final entry in state.webSendState!.files.entries) entry.key: entry.value.file,
},
).toJson());
});
router.get(ApiRoute.download.v2, (Request request) async {
final sessionId = request.url.queryParameters['sessionId'];
if (sessionId == null) {
return server.responseJson(400, message: 'Missing sessionId.');
}
final session = server.getState().webSendState?.sessions[sessionId];
if (session == null || session.responseHandler != null || session.ip != request.ip) {
return server.responseJson(403, message: 'Invalid sessionId.');
}
final fileId = request.url.queryParameters['fileId'];
if (fileId == null) {
return server.responseJson(400, message: 'Missing fileId.');
}
final file = server.getState().webSendState?.files[fileId];
if (file == null) {
return server.responseJson(403, message: 'Invalid fileId.');
}
final fileName = file.file.fileName.replaceAll('/', '-'); // File name may be inside directories
final headers = {
'content-type': 'application/octet-stream',
'content-disposition': 'attachment; filename="${Uri.encodeComponent(fileName)}"',
'content-length': '${file.file.size}',
};
if (file.bytes != null) {
return Response(
200,
body: file.bytes!,
headers: headers,
);
} else {
return Response(
200,
body: File(file.path!).openRead().asBroadcastStream(),
headers: headers,
);
}
});
}
Future<void> initializeWebSend({required List<CrossFile> files}) async {
final webSendState = WebSendState(
sessions: {},
files: Map.fromEntries(await Future.wait(files.map((file) async {
final id = _uuid.v4();
return MapEntry(
id,
WebSendFile(
file: FileDto(
id: id,
fileName: file.name,
size: file.size,
fileType: file.fileType,
hash: null,
preview: files.first.fileType == FileType.text && files.first.bytes != null
? utf8.decode(files.first.bytes!) // send simple message by embedding it into the preview
: null,
legacy: false,
),
asset: file.asset,
path: file.path,
bytes: file.bytes,
),
);
}))),
autoAccept: server.ref.read(settingsProvider).shareViaLinkAutoAccept,
);
server.setState(
(oldState) => oldState?.copyWith(
webSendState: webSendState,
),
);
}
void acceptRequest(String sessionId) {
_respondRequest(sessionId, true);
}
void declineRequest(String sessionId) {
_respondRequest(sessionId, false);
}
void _respondRequest(String sessionId, bool accepted) {
final controller = server.getState().webSendState?.sessions[sessionId]?.responseHandler;
if (controller == null) {
return;
}
controller.add(accepted);
controller.close(); // ignore: discarded_futures
}
}
extension on WebSendState {
WebSendState updateSession({
required String sessionId,
required WebSendSession Function(WebSendSession oldSession) update,
}) {
return copyWith(
sessions: {...sessions}..update(
sessionId,
(session) => update(session),
),
);
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/logging/discovery_logs_provider.dart | import 'package:localsend_app/model/log_entry.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _logger = Logger('Discovery');
/// Contains the discovery logs for debugging purposes.
final discoveryLoggerProvider = NotifierProvider<DiscoveryLogger, List<LogEntry>>((ref) {
return DiscoveryLogger();
});
class DiscoveryLogger extends Notifier<List<LogEntry>> {
DiscoveryLogger();
@override
List<LogEntry> init() {
return [];
}
void addLog(String log) {
_logger.info(log);
state = [
...state,
LogEntry(timestamp: DateTime.now(), log: log),
].take(200).toList();
}
void clear() {
state = [];
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/logging/http_logs_provider.dart | import 'package:localsend_app/model/log_entry.dart';
import 'package:logging/logging.dart';
import 'package:refena_flutter/refena_flutter.dart';
final _logger = Logger('HTTP');
/// Contains the discovery logs for debugging purposes.
final httpLogsProvider = NotifierProvider<HttpLogsService, List<LogEntry>>((ref) {
return HttpLogsService();
});
class HttpLogsService extends Notifier<List<LogEntry>> {
@override
List<LogEntry> init() {
return [];
}
void addLog(String log) {
_logger.info(log);
state = [
...state,
LogEntry(timestamp: DateTime.now(), log: log),
].take(200).toList();
}
void clear() {
state = [];
}
@override
String describeState(List<LogEntry> state) => '${state.length} logs';
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/selection/selected_sending_files_provider.dart | import 'dart:convert' show utf8;
import 'dart:io';
import 'dart:typed_data';
import 'package:common/common.dart';
import 'package:localsend_app/model/cross_file.dart';
import 'package:localsend_app/util/file_path_helper.dart';
import 'package:localsend_app/util/native/cache_helper.dart';
import 'package:localsend_app/util/native/cross_file_converters.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import 'package:refena_flutter/refena_flutter.dart';
import 'package:uuid/uuid.dart';
final _logger = Logger('SelectedSendingFiles');
const _uuid = Uuid();
/// Manages files selected for sending.
/// Will stay alive even after a session has been completed to send the same files to another device.
final selectedSendingFilesProvider = ReduxProvider<SelectedSendingFilesNotifier, List<CrossFile>>((ref) {
return SelectedSendingFilesNotifier();
});
class SelectedSendingFilesNotifier extends ReduxNotifier<List<CrossFile>> {
@override
List<CrossFile> init() => [];
}
/// Adds a message.
class AddMessageAction extends ReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> {
final String message;
final int? index;
AddMessageAction({
required this.message,
this.index,
});
@override
List<CrossFile> reduce() {
final List<int> bytes = utf8.encode(message);
final file = CrossFile(
name: '${_uuid.v4()}.txt',
fileType: FileType.text,
size: bytes.length,
thumbnail: null,
asset: null,
path: null,
bytes: bytes,
);
return List.unmodifiable([
...state,
]..insert(index ?? state.length, file));
}
}
/// Updates a message.
class UpdateMessageAction extends ReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> {
final String message;
final int index;
UpdateMessageAction({
required this.message,
required this.index,
});
@override
List<CrossFile> reduce() {
dispatch(RemoveSelectedFileAction(index));
dispatch(AddMessageAction(message: message, index: index));
return state;
}
}
/// Adds a binary file to the list.
/// During the sending process, the file will be read from the memory.
class AddBinaryAction extends ReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> {
final Uint8List bytes;
final FileType fileType;
final String fileName;
AddBinaryAction({
required this.bytes,
required this.fileType,
required this.fileName,
});
@override
List<CrossFile> reduce() {
final file = CrossFile(
name: fileName,
fileType: fileType,
size: bytes.length,
thumbnail: fileType == FileType.image ? bytes : null,
asset: null,
path: null,
bytes: bytes,
);
return List.unmodifiable([
...state,
file,
]);
}
}
/// Adds one or more files to the list.
class AddFilesAction<T> extends AsyncReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> {
final Iterable<T> files;
final Future<CrossFile> Function(T) converter;
AddFilesAction({
required this.files,
required this.converter,
});
@override
Future<List<CrossFile>> reduce() async {
final newFiles = <CrossFile>[];
for (final file in files) {
// we do it sequential because there are bugs
// https://github.com/fluttercandies/flutter_photo_manager/issues/589
final crossFile = await converter(file);
final isAlreadySelect = state.any((element) => element.isSameFile(otherFile: crossFile));
if (!isAlreadySelect) {
newFiles.add(crossFile);
}
}
return List.unmodifiable([
...state,
...newFiles,
]);
}
}
/// Adds files inside the directory recursively.
class AddDirectoryAction extends AsyncReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> {
final String directoryPath;
AddDirectoryAction(this.directoryPath);
@override
Future<List<CrossFile>> reduce() async {
_logger.info('Reading files in $directoryPath');
final newFiles = <CrossFile>[];
final directoryName = p.basename(directoryPath);
await for (final entity in Directory(directoryPath).list(recursive: true)) {
if (entity is File) {
final relative = '$directoryName/${p.relative(entity.path, from: directoryPath).replaceAll('\\', '/')}';
_logger.info('Add file $relative');
final file = CrossFile(
name: relative,
fileType: relative.guessFileType(),
size: entity.lengthSync(),
thumbnail: null,
asset: null,
path: entity.path,
bytes: null,
);
final isAlreadySelect = state.any((element) => element.isSameFile(otherFile: file));
if (!isAlreadySelect) {
newFiles.add(file);
}
}
}
return List.unmodifiable([
...state,
...newFiles,
]);
}
}
/// Removes a file at the given [index].
class RemoveSelectedFileAction extends ReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> with GlobalActions {
final int index;
RemoveSelectedFileAction(this.index);
@override
List<CrossFile> reduce() {
return List<CrossFile>.unmodifiable([...state]..removeAt(index));
}
@override
void after() {
if (state.isEmpty) {
global.dispatchAsync(ClearCacheAction()); // ignore: discarded_futures
}
}
}
/// Removes all files from the list.
class ClearSelectionAction extends ReduxAction<SelectedSendingFilesNotifier, List<CrossFile>> with GlobalActions {
@override
List<CrossFile> reduce() {
return const [];
}
@override
void after() {
global.dispatchAsync(ClearCacheAction()); // ignore: discarded_futures
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/selection/selected_receiving_files_provider.dart | import 'package:collection/collection.dart';
import 'package:common/common.dart';
import 'package:localsend_app/util/file_path_helper.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:uuid/uuid.dart';
const _uuid = Uuid();
/// Manages files to be selected to receive.
/// Only alive during [ReceivePage], i.e. this provider gets disposed as soon as the actual file transfer begin.
/// Map: FileId -> FileName
final selectedReceivingFilesProvider = NotifierProvider<SelectedReceivingFilesNotifier, Map<String, String>>((ref) {
return SelectedReceivingFilesNotifier();
});
class SelectedReceivingFilesNotifier extends Notifier<Map<String, String>> {
SelectedReceivingFilesNotifier();
@override
Map<String, String> init() {
return {};
}
void setFiles(List<FileDto> files) {
state = {
for (final f in files) f.id: f.fileName, // by default, accept all files and take their original name
};
}
void unselect(String fileId) {
state = {...state}..remove(fileId);
}
void select(FileDto file) {
state = {
...state,
file.id: file.fileName,
};
}
void rename(String fileId, String fileName) {
state = {...state}..update(fileId, (_) => fileName);
}
void applyRandom() {
state = {
for (final entry in state.entries) entry.key: entry.value.withFileNameKeepExtension(_uuid.v4()),
};
}
void applyCounter({
required String prefix,
required bool padZero,
required bool sortFirst,
}) {
final files = state.entries.toList();
if (sortFirst) {
files.sort((a, b) => a.value.compareTo(b.value));
}
final maxKeyStringLength = files.length.toString().length;
state = Map.fromEntries(files.mapIndexed((index, element) {
String number = (index + 1).toString();
if (padZero) {
number.padLeft(maxKeyStringLength, '0');
}
return MapEntry(element.key, element.value.withFileNameKeepExtension('$prefix$number'));
}));
}
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/param/apk_provider_param.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'apk_provider_param.dart';
class ApkProviderParamMapper extends ClassMapperBase<ApkProviderParam> {
ApkProviderParamMapper._();
static ApkProviderParamMapper? _instance;
static ApkProviderParamMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = ApkProviderParamMapper._());
}
return _instance!;
}
@override
final String id = 'ApkProviderParam';
static String _$query(ApkProviderParam v) => v.query;
static const Field<ApkProviderParam, String> _f$query = Field('query', _$query);
static bool _$includeSystemApps(ApkProviderParam v) => v.includeSystemApps;
static const Field<ApkProviderParam, bool> _f$includeSystemApps = Field('includeSystemApps', _$includeSystemApps);
static bool _$onlyAppsWithLaunchIntent(ApkProviderParam v) => v.onlyAppsWithLaunchIntent;
static const Field<ApkProviderParam, bool> _f$onlyAppsWithLaunchIntent = Field('onlyAppsWithLaunchIntent', _$onlyAppsWithLaunchIntent);
@override
final MappableFields<ApkProviderParam> fields = const {
#query: _f$query,
#includeSystemApps: _f$includeSystemApps,
#onlyAppsWithLaunchIntent: _f$onlyAppsWithLaunchIntent,
};
static ApkProviderParam _instantiate(DecodingData data) {
return ApkProviderParam(
query: data.dec(_f$query),
includeSystemApps: data.dec(_f$includeSystemApps),
onlyAppsWithLaunchIntent: data.dec(_f$onlyAppsWithLaunchIntent));
}
@override
final Function instantiate = _instantiate;
static ApkProviderParam fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<ApkProviderParam>(map);
}
static ApkProviderParam deserialize(String json) {
return ensureInitialized().decodeJson<ApkProviderParam>(json);
}
}
mixin ApkProviderParamMappable {
String serialize() {
return ApkProviderParamMapper.ensureInitialized().encodeJson<ApkProviderParam>(this as ApkProviderParam);
}
Map<String, dynamic> toJson() {
return ApkProviderParamMapper.ensureInitialized().encodeMap<ApkProviderParam>(this as ApkProviderParam);
}
ApkProviderParamCopyWith<ApkProviderParam, ApkProviderParam, ApkProviderParam> get copyWith =>
_ApkProviderParamCopyWithImpl(this as ApkProviderParam, $identity, $identity);
@override
String toString() {
return ApkProviderParamMapper.ensureInitialized().stringifyValue(this as ApkProviderParam);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && ApkProviderParamMapper.ensureInitialized().isValueEqual(this as ApkProviderParam, other));
}
@override
int get hashCode {
return ApkProviderParamMapper.ensureInitialized().hashValue(this as ApkProviderParam);
}
}
extension ApkProviderParamValueCopy<$R, $Out> on ObjectCopyWith<$R, ApkProviderParam, $Out> {
ApkProviderParamCopyWith<$R, ApkProviderParam, $Out> get $asApkProviderParam => $base.as((v, t, t2) => _ApkProviderParamCopyWithImpl(v, t, t2));
}
abstract class ApkProviderParamCopyWith<$R, $In extends ApkProviderParam, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call({String? query, bool? includeSystemApps, bool? onlyAppsWithLaunchIntent});
ApkProviderParamCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _ApkProviderParamCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, ApkProviderParam, $Out>
implements ApkProviderParamCopyWith<$R, ApkProviderParam, $Out> {
_ApkProviderParamCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<ApkProviderParam> $mapper = ApkProviderParamMapper.ensureInitialized();
@override
$R call({String? query, bool? includeSystemApps, bool? onlyAppsWithLaunchIntent}) => $apply(FieldCopyWithData({
if (query != null) #query: query,
if (includeSystemApps != null) #includeSystemApps: includeSystemApps,
if (onlyAppsWithLaunchIntent != null) #onlyAppsWithLaunchIntent: onlyAppsWithLaunchIntent
}));
@override
ApkProviderParam $make(CopyWithData data) => ApkProviderParam(
query: data.get(#query, or: $value.query),
includeSystemApps: data.get(#includeSystemApps, or: $value.includeSystemApps),
onlyAppsWithLaunchIntent: data.get(#onlyAppsWithLaunchIntent, or: $value.onlyAppsWithLaunchIntent));
@override
ApkProviderParamCopyWith<$R2, ApkProviderParam, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) => _ApkProviderParamCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/param/cached_apk_provider_param.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'cached_apk_provider_param.dart';
class CachedApkProviderParamMapper extends ClassMapperBase<CachedApkProviderParam> {
CachedApkProviderParamMapper._();
static CachedApkProviderParamMapper? _instance;
static CachedApkProviderParamMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = CachedApkProviderParamMapper._());
}
return _instance!;
}
@override
final String id = 'CachedApkProviderParam';
static bool _$includeSystemApps(CachedApkProviderParam v) => v.includeSystemApps;
static const Field<CachedApkProviderParam, bool> _f$includeSystemApps = Field('includeSystemApps', _$includeSystemApps);
static bool _$onlyAppsWithLaunchIntent(CachedApkProviderParam v) => v.onlyAppsWithLaunchIntent;
static const Field<CachedApkProviderParam, bool> _f$onlyAppsWithLaunchIntent = Field('onlyAppsWithLaunchIntent', _$onlyAppsWithLaunchIntent);
@override
final MappableFields<CachedApkProviderParam> fields = const {
#includeSystemApps: _f$includeSystemApps,
#onlyAppsWithLaunchIntent: _f$onlyAppsWithLaunchIntent,
};
static CachedApkProviderParam _instantiate(DecodingData data) {
return CachedApkProviderParam(includeSystemApps: data.dec(_f$includeSystemApps), onlyAppsWithLaunchIntent: data.dec(_f$onlyAppsWithLaunchIntent));
}
@override
final Function instantiate = _instantiate;
static CachedApkProviderParam fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<CachedApkProviderParam>(map);
}
static CachedApkProviderParam deserialize(String json) {
return ensureInitialized().decodeJson<CachedApkProviderParam>(json);
}
}
mixin CachedApkProviderParamMappable {
String serialize() {
return CachedApkProviderParamMapper.ensureInitialized().encodeJson<CachedApkProviderParam>(this as CachedApkProviderParam);
}
Map<String, dynamic> toJson() {
return CachedApkProviderParamMapper.ensureInitialized().encodeMap<CachedApkProviderParam>(this as CachedApkProviderParam);
}
CachedApkProviderParamCopyWith<CachedApkProviderParam, CachedApkProviderParam, CachedApkProviderParam> get copyWith =>
_CachedApkProviderParamCopyWithImpl(this as CachedApkProviderParam, $identity, $identity);
@override
String toString() {
return CachedApkProviderParamMapper.ensureInitialized().stringifyValue(this as CachedApkProviderParam);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType && CachedApkProviderParamMapper.ensureInitialized().isValueEqual(this as CachedApkProviderParam, other));
}
@override
int get hashCode {
return CachedApkProviderParamMapper.ensureInitialized().hashValue(this as CachedApkProviderParam);
}
}
extension CachedApkProviderParamValueCopy<$R, $Out> on ObjectCopyWith<$R, CachedApkProviderParam, $Out> {
CachedApkProviderParamCopyWith<$R, CachedApkProviderParam, $Out> get $asCachedApkProviderParam =>
$base.as((v, t, t2) => _CachedApkProviderParamCopyWithImpl(v, t, t2));
}
abstract class CachedApkProviderParamCopyWith<$R, $In extends CachedApkProviderParam, $Out> implements ClassCopyWith<$R, $In, $Out> {
$R call({bool? includeSystemApps, bool? onlyAppsWithLaunchIntent});
CachedApkProviderParamCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _CachedApkProviderParamCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, CachedApkProviderParam, $Out>
implements CachedApkProviderParamCopyWith<$R, CachedApkProviderParam, $Out> {
_CachedApkProviderParamCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<CachedApkProviderParam> $mapper = CachedApkProviderParamMapper.ensureInitialized();
@override
$R call({bool? includeSystemApps, bool? onlyAppsWithLaunchIntent}) => $apply(FieldCopyWithData({
if (includeSystemApps != null) #includeSystemApps: includeSystemApps,
if (onlyAppsWithLaunchIntent != null) #onlyAppsWithLaunchIntent: onlyAppsWithLaunchIntent
}));
@override
CachedApkProviderParam $make(CopyWithData data) => CachedApkProviderParam(
includeSystemApps: data.get(#includeSystemApps, or: $value.includeSystemApps),
onlyAppsWithLaunchIntent: data.get(#onlyAppsWithLaunchIntent, or: $value.onlyAppsWithLaunchIntent));
@override
CachedApkProviderParamCopyWith<$R2, CachedApkProviderParam, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_CachedApkProviderParamCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/param/apk_provider_param.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'apk_provider_param.mapper.dart';
@MappableClass()
class ApkProviderParam with ApkProviderParamMappable {
final String query;
final bool includeSystemApps;
final bool onlyAppsWithLaunchIntent;
const ApkProviderParam({
required this.query,
required this.includeSystemApps,
required this.onlyAppsWithLaunchIntent,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/param/cached_apk_provider_param.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'cached_apk_provider_param.mapper.dart';
@MappableClass()
class CachedApkProviderParam with CachedApkProviderParamMappable {
final bool includeSystemApps;
final bool onlyAppsWithLaunchIntent;
const CachedApkProviderParam({
required this.includeSystemApps,
required this.onlyAppsWithLaunchIntent,
});
}
| 0 |
mirrored_repositories/localsend/app/lib/provider | mirrored_repositories/localsend/app/lib/provider/ui/home_tab_provider.dart | import 'package:localsend_app/pages/home_page.dart';
import 'package:refena_flutter/refena_flutter.dart';
/// This provider is used so that tabs know if they are currently visible.
/// The [HomePage] is responsible for setting the current tab.
final homeTabProvider = ReduxProvider<HomeTabNotifier, HomeTab>((ref) => HomeTabNotifier());
class HomeTabNotifier extends ReduxNotifier<HomeTab> {
@override
HomeTab init() => HomeTab.receive;
}
class SetHomeTabAction extends ReduxAction<HomeTabNotifier, HomeTab> {
final HomeTab tab;
SetHomeTabAction(this.tab);
@override
HomeTab reduce() => tab;
}
| 0 |
mirrored_repositories/localsend/app | mirrored_repositories/localsend/app/test/mocks.dart | import 'package:localsend_app/provider/persistence_provider.dart';
import 'package:mockito/annotations.dart';
import 'package:shared_preferences/shared_preferences.dart';
@GenerateNiceMocks([
MockSpec<PersistenceService>(),
MockSpec<SharedPreferences>(),
])
void main() {}
| 0 |
mirrored_repositories/localsend/app | mirrored_repositories/localsend/app/test/mocks.mocks.dart | // Mocks generated by Mockito 5.4.4 from annotations
// in localsend_app/test/mocks.dart.
// Do not manually edit this file.
// ignore_for_file: no_leading_underscores_for_library_prefixes
import 'dart:async' as _i4;
import 'dart:ui' as _i12;
import 'package:common/common.dart' as _i2;
import 'package:flutter/material.dart' as _i8;
import 'package:localsend_app/gen/strings.g.dart' as _i10;
import 'package:localsend_app/model/persistence/color_mode.dart' as _i9;
import 'package:localsend_app/model/persistence/favorite_device.dart' as _i6;
import 'package:localsend_app/model/persistence/receive_history_entry.dart' as _i5;
import 'package:localsend_app/model/send_mode.dart' as _i11;
import 'package:localsend_app/provider/persistence_provider.dart' as _i3;
import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i7;
import 'package:shared_preferences/shared_preferences.dart' as _i13;
// ignore_for_file: type=lint
// ignore_for_file: avoid_redundant_argument_values
// ignore_for_file: avoid_setters_without_getters
// ignore_for_file: comment_references
// ignore_for_file: deprecated_member_use
// ignore_for_file: deprecated_member_use_from_same_package
// ignore_for_file: implementation_imports
// ignore_for_file: invalid_use_of_visible_for_testing_member
// ignore_for_file: prefer_const_constructors
// ignore_for_file: unnecessary_parenthesis
// ignore_for_file: camel_case_types
// ignore_for_file: subtype_of_sealed_class
class _FakeStoredSecurityContext_0 extends _i1.SmartFake implements _i2.StoredSecurityContext {
_FakeStoredSecurityContext_0(
Object parent,
Invocation parentInvocation,
) : super(
parent,
parentInvocation,
);
}
/// A class which mocks [PersistenceService].
///
/// See the documentation for Mockito's code generation for more information.
class MockPersistenceService extends _i1.Mock implements _i3.PersistenceService {
@override
_i2.StoredSecurityContext getSecurityContext() => (super.noSuchMethod(
Invocation.method(
#getSecurityContext,
[],
),
returnValue: _FakeStoredSecurityContext_0(
this,
Invocation.method(
#getSecurityContext,
[],
),
),
returnValueForMissingStub: _FakeStoredSecurityContext_0(
this,
Invocation.method(
#getSecurityContext,
[],
),
),
) as _i2.StoredSecurityContext);
@override
_i4.Future<void> setSecurityContext(_i2.StoredSecurityContext? context) => (super.noSuchMethod(
Invocation.method(
#setSecurityContext,
[context],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
List<_i5.ReceiveHistoryEntry> getReceiveHistory() => (super.noSuchMethod(
Invocation.method(
#getReceiveHistory,
[],
),
returnValue: <_i5.ReceiveHistoryEntry>[],
returnValueForMissingStub: <_i5.ReceiveHistoryEntry>[],
) as List<_i5.ReceiveHistoryEntry>);
@override
_i4.Future<void> setReceiveHistory(List<_i5.ReceiveHistoryEntry>? entries) => (super.noSuchMethod(
Invocation.method(
#setReceiveHistory,
[entries],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
List<_i6.FavoriteDevice> getFavorites() => (super.noSuchMethod(
Invocation.method(
#getFavorites,
[],
),
returnValue: <_i6.FavoriteDevice>[],
returnValueForMissingStub: <_i6.FavoriteDevice>[],
) as List<_i6.FavoriteDevice>);
@override
_i4.Future<void> setFavorites(List<_i6.FavoriteDevice>? entries) => (super.noSuchMethod(
Invocation.method(
#setFavorites,
[entries],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
String getShowToken() => (super.noSuchMethod(
Invocation.method(
#getShowToken,
[],
),
returnValue: _i7.dummyValue<String>(
this,
Invocation.method(
#getShowToken,
[],
),
),
returnValueForMissingStub: _i7.dummyValue<String>(
this,
Invocation.method(
#getShowToken,
[],
),
),
) as String);
@override
String getAlias() => (super.noSuchMethod(
Invocation.method(
#getAlias,
[],
),
returnValue: _i7.dummyValue<String>(
this,
Invocation.method(
#getAlias,
[],
),
),
returnValueForMissingStub: _i7.dummyValue<String>(
this,
Invocation.method(
#getAlias,
[],
),
),
) as String);
@override
_i4.Future<void> setAlias(String? alias) => (super.noSuchMethod(
Invocation.method(
#setAlias,
[alias],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i8.ThemeMode getTheme() => (super.noSuchMethod(
Invocation.method(
#getTheme,
[],
),
returnValue: _i8.ThemeMode.system,
returnValueForMissingStub: _i8.ThemeMode.system,
) as _i8.ThemeMode);
@override
_i4.Future<void> setTheme(_i8.ThemeMode? theme) => (super.noSuchMethod(
Invocation.method(
#setTheme,
[theme],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i9.ColorMode getColorMode() => (super.noSuchMethod(
Invocation.method(
#getColorMode,
[],
),
returnValue: _i9.ColorMode.system,
returnValueForMissingStub: _i9.ColorMode.system,
) as _i9.ColorMode);
@override
_i4.Future<void> setColorMode(_i9.ColorMode? color) => (super.noSuchMethod(
Invocation.method(
#setColorMode,
[color],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setLocale(_i10.AppLocale? locale) => (super.noSuchMethod(
Invocation.method(
#setLocale,
[locale],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
int getPort() => (super.noSuchMethod(
Invocation.method(
#getPort,
[],
),
returnValue: 0,
returnValueForMissingStub: 0,
) as int);
@override
_i4.Future<void> setPort(int? port) => (super.noSuchMethod(
Invocation.method(
#setPort,
[port],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool getShareViaLinkAutoAccept() => (super.noSuchMethod(
Invocation.method(
#getShareViaLinkAutoAccept,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setShareViaLinkAutoAccept(bool? shareViaLinkAutoAccept) => (super.noSuchMethod(
Invocation.method(
#setShareViaLinkAutoAccept,
[shareViaLinkAutoAccept],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
String getMulticastGroup() => (super.noSuchMethod(
Invocation.method(
#getMulticastGroup,
[],
),
returnValue: _i7.dummyValue<String>(
this,
Invocation.method(
#getMulticastGroup,
[],
),
),
returnValueForMissingStub: _i7.dummyValue<String>(
this,
Invocation.method(
#getMulticastGroup,
[],
),
),
) as String);
@override
_i4.Future<void> setMulticastGroup(String? group) => (super.noSuchMethod(
Invocation.method(
#setMulticastGroup,
[group],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setDestination(String? destination) => (super.noSuchMethod(
Invocation.method(
#setDestination,
[destination],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isSaveToGallery() => (super.noSuchMethod(
Invocation.method(
#isSaveToGallery,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setSaveToGallery(bool? saveToGallery) => (super.noSuchMethod(
Invocation.method(
#setSaveToGallery,
[saveToGallery],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isSaveToHistory() => (super.noSuchMethod(
Invocation.method(
#isSaveToHistory,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setSaveToHistory(bool? saveToHistory) => (super.noSuchMethod(
Invocation.method(
#setSaveToHistory,
[saveToHistory],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isQuickSave() => (super.noSuchMethod(
Invocation.method(
#isQuickSave,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setQuickSave(bool? quickSave) => (super.noSuchMethod(
Invocation.method(
#setQuickSave,
[quickSave],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isAutoFinish() => (super.noSuchMethod(
Invocation.method(
#isAutoFinish,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setAutoFinish(bool? autoFinish) => (super.noSuchMethod(
Invocation.method(
#setAutoFinish,
[autoFinish],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isMinimizeToTray() => (super.noSuchMethod(
Invocation.method(
#isMinimizeToTray,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setMinimizeToTray(bool? minimizeToTray) => (super.noSuchMethod(
Invocation.method(
#setMinimizeToTray,
[minimizeToTray],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isLaunchAtStartup() => (super.noSuchMethod(
Invocation.method(
#isLaunchAtStartup,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setLaunchAtStartup(bool? launchAtStartup) => (super.noSuchMethod(
Invocation.method(
#setLaunchAtStartup,
[launchAtStartup],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isAutoStartLaunchMinimized() => (super.noSuchMethod(
Invocation.method(
#isAutoStartLaunchMinimized,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setAutoStartLaunchMinimized(bool? launchMinimized) => (super.noSuchMethod(
Invocation.method(
#setAutoStartLaunchMinimized,
[launchMinimized],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool isHttps() => (super.noSuchMethod(
Invocation.method(
#isHttps,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setHttps(bool? https) => (super.noSuchMethod(
Invocation.method(
#setHttps,
[https],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i11.SendMode getSendMode() => (super.noSuchMethod(
Invocation.method(
#getSendMode,
[],
),
returnValue: _i11.SendMode.single,
returnValueForMissingStub: _i11.SendMode.single,
) as _i11.SendMode);
@override
_i4.Future<void> setSendMode(_i11.SendMode? mode) => (super.noSuchMethod(
Invocation.method(
#setSendMode,
[mode],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setWindowOffsetX(double? x) => (super.noSuchMethod(
Invocation.method(
#setWindowOffsetX,
[x],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setWindowOffsetY(double? y) => (super.noSuchMethod(
Invocation.method(
#setWindowOffsetY,
[y],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setWindowHeight(double? height) => (super.noSuchMethod(
Invocation.method(
#setWindowHeight,
[height],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setWindowWidth(double? width) => (super.noSuchMethod(
Invocation.method(
#setWindowWidth,
[width],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
Map<String, _i12.OffsetBase?> getWindowLastDimensions() => (super.noSuchMethod(
Invocation.method(
#getWindowLastDimensions,
[],
),
returnValue: <String, _i12.OffsetBase?>{},
returnValueForMissingStub: <String, _i12.OffsetBase?>{},
) as Map<String, _i12.OffsetBase?>);
@override
_i4.Future<void> setSaveWindowPlacement(bool? savePlacement) => (super.noSuchMethod(
Invocation.method(
#setSaveWindowPlacement,
[savePlacement],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool getSaveWindowPlacement() => (super.noSuchMethod(
Invocation.method(
#getSaveWindowPlacement,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setEnableAnimations(bool? enableAnimations) => (super.noSuchMethod(
Invocation.method(
#setEnableAnimations,
[enableAnimations],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
bool getEnableAnimations() => (super.noSuchMethod(
Invocation.method(
#getEnableAnimations,
[],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
_i4.Future<void> setDeviceType(_i2.DeviceType? deviceType) => (super.noSuchMethod(
Invocation.method(
#setDeviceType,
[deviceType],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> setDeviceModel(String? deviceModel) => (super.noSuchMethod(
Invocation.method(
#setDeviceModel,
[deviceModel],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
@override
_i4.Future<void> clear() => (super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
}
/// A class which mocks [SharedPreferences].
///
/// See the documentation for Mockito's code generation for more information.
class MockSharedPreferences extends _i1.Mock implements _i13.SharedPreferences {
@override
Set<String> getKeys() => (super.noSuchMethod(
Invocation.method(
#getKeys,
[],
),
returnValue: <String>{},
returnValueForMissingStub: <String>{},
) as Set<String>);
@override
Object? get(String? key) => (super.noSuchMethod(
Invocation.method(
#get,
[key],
),
returnValueForMissingStub: null,
) as Object?);
@override
bool? getBool(String? key) => (super.noSuchMethod(
Invocation.method(
#getBool,
[key],
),
returnValueForMissingStub: null,
) as bool?);
@override
int? getInt(String? key) => (super.noSuchMethod(
Invocation.method(
#getInt,
[key],
),
returnValueForMissingStub: null,
) as int?);
@override
double? getDouble(String? key) => (super.noSuchMethod(
Invocation.method(
#getDouble,
[key],
),
returnValueForMissingStub: null,
) as double?);
@override
String? getString(String? key) => (super.noSuchMethod(
Invocation.method(
#getString,
[key],
),
returnValueForMissingStub: null,
) as String?);
@override
bool containsKey(String? key) => (super.noSuchMethod(
Invocation.method(
#containsKey,
[key],
),
returnValue: false,
returnValueForMissingStub: false,
) as bool);
@override
List<String>? getStringList(String? key) => (super.noSuchMethod(
Invocation.method(
#getStringList,
[key],
),
returnValueForMissingStub: null,
) as List<String>?);
@override
_i4.Future<bool> setBool(
String? key,
bool? value,
) =>
(super.noSuchMethod(
Invocation.method(
#setBool,
[
key,
value,
],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> setInt(
String? key,
int? value,
) =>
(super.noSuchMethod(
Invocation.method(
#setInt,
[
key,
value,
],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> setDouble(
String? key,
double? value,
) =>
(super.noSuchMethod(
Invocation.method(
#setDouble,
[
key,
value,
],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> setString(
String? key,
String? value,
) =>
(super.noSuchMethod(
Invocation.method(
#setString,
[
key,
value,
],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> setStringList(
String? key,
List<String>? value,
) =>
(super.noSuchMethod(
Invocation.method(
#setStringList,
[
key,
value,
],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> remove(String? key) => (super.noSuchMethod(
Invocation.method(
#remove,
[key],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> commit() => (super.noSuchMethod(
Invocation.method(
#commit,
[],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<bool> clear() => (super.noSuchMethod(
Invocation.method(
#clear,
[],
),
returnValue: _i4.Future<bool>.value(false),
returnValueForMissingStub: _i4.Future<bool>.value(false),
) as _i4.Future<bool>);
@override
_i4.Future<void> reload() => (super.noSuchMethod(
Invocation.method(
#reload,
[],
),
returnValue: _i4.Future<void>.value(),
returnValueForMissingStub: _i4.Future<void>.value(),
) as _i4.Future<void>);
}
| 0 |
mirrored_repositories/localsend/app/test | mirrored_repositories/localsend/app/test/unit/i18n_test.dart | import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:localsend_app/gen/strings.g.dart';
import 'package:test/test.dart';
void main() {
group('i18n', () {
test('Should compile', () {
// The following test will fail if the i18n file is either not compiled
// or there are compile-time errors.
expect(AppLocale.en.translations.general.accept, 'Accept');
});
test('All locales should be supported by Flutter', () {
for (final locale in AppLocale.values) {
expect(kMaterialSupportedLanguages, contains(locale.languageCode));
}
});
});
}
| 0 |
mirrored_repositories/localsend/app/test/unit/model | mirrored_repositories/localsend/app/test/unit/model/dto/prepare_upload_request_dto_test.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
import 'package:test/test.dart';
void main() {
MapperContainer.globals.use(const FileDtoMapper());
group('parse PrepareUploadRequestDto', () {
test('should parse valid enums', () {
final dto = {
'info': {
'alias': 'Nice Banana',
'deviceModel': 'Samsung',
'deviceType': 'mobile',
},
'files': {
'some id': {
'id': 'some id',
'fileName': 'another image.jpg',
'size': 1234,
'fileType': 'image',
'preview': '*preview data*',
}
}
};
final parsed = PrepareUploadRequestDto.fromJson(dto);
expect(parsed.info.deviceType, DeviceType.mobile);
expect(parsed.files.length, 1);
expect(parsed.files.values.first.fileType, FileType.image);
});
test('Should fallback deviceType (simple)', () {
final dto = {
'alias': 'Nice Banana',
'deviceModel': 'Samsung',
'deviceType': 'invalidType',
};
final parsed = InfoRegisterDto.fromJson(dto);
expect(parsed.deviceType, DeviceType.desktop);
});
test('should fallback deviceType', () {
final dto = {
'info': {
'alias': 'Nice Banana',
'deviceModel': 'Samsung',
'deviceType': 'invalidType',
},
'files': {
'some id': {
'id': 'some id',
'fileName': 'another image.jpg',
'size': 1234,
'fileType': 'image',
'preview': '*preview data*',
}
}
};
final parsed = PrepareUploadRequestDto.fromJson(dto);
expect(parsed.info.deviceType, DeviceType.desktop);
expect(parsed.files.length, 1);
expect(parsed.files.values.first.fileType, FileType.image);
});
test('should fallback fileType', () {
final dto = {
'info': {
'alias': 'Nice Banana',
'deviceModel': 'Samsung',
'deviceType': 'mobile',
},
'files': {
'some id': {
'id': 'some id',
'fileName': 'another image.jpg',
'size': 1234,
'fileType': 'superBigImage',
'preview': '*preview data*',
}
}
};
final parsed = PrepareUploadRequestDto.fromJson(dto);
expect(parsed.info.deviceType, DeviceType.mobile);
expect(parsed.files.length, 1);
expect(parsed.files.values.first.fileType, FileType.other);
});
test('should parse mime type', () {
final dto = {
'info': {
'alias': 'Nice Banana',
'deviceModel': 'Samsung',
'deviceType': 'mobile',
},
'files': {
'some id': {
'id': 'some id',
'fileName': 'another image.jpg',
'size': 1234,
'fileType': 'image/jpeg',
'preview': '*preview data*',
}
}
};
final parsed = PrepareUploadRequestDto.fromJson(dto);
expect(parsed.info.deviceType, DeviceType.mobile);
expect(parsed.files.length, 1);
expect(parsed.files.values.first.fileType, FileType.image);
});
test('should parse apk mime type', () {
final dto = {
'info': {
'alias': 'Nice Banana',
'deviceModel': 'Samsung',
'deviceType': 'mobile',
},
'files': {
'some id': {
'id': 'some id',
'fileName': 'myApk.apk',
'size': 1234,
'fileType': 'application/vnd.android.package-archive',
}
}
};
final parsed = PrepareUploadRequestDto.fromJson(dto);
expect(parsed.info.deviceType, DeviceType.mobile);
expect(parsed.files.length, 1);
expect(parsed.files.values.first.fileType, FileType.apk);
});
});
group('serialize PrepareUploadRequestDto', () {
const info = InfoRegisterDto(
alias: 'Nice Banana',
version: '2.0',
deviceModel: 'Samsung',
deviceType: DeviceType.mobile,
fingerprint: '123',
port: 123,
protocol: ProtocolType.http,
download: false,
);
test('should serialize in legacy mode', () {
const dto = PrepareUploadRequestDto(
info: info,
files: {
'some id': FileDto(
id: 'some id',
fileName: 'another image.jpg',
size: 1234,
fileType: FileType.image,
hash: '*hash*',
preview: '*preview data*',
legacy: true,
),
'some id 2': FileDto(
id: 'some id 2',
fileName: 'my apk.apk',
size: 1234,
fileType: FileType.apk,
hash: '*hash*',
preview: '*preview data*',
legacy: true,
),
},
);
final serialized = dto.toJson();
expect(serialized['info']['deviceType'], 'mobile');
expect(serialized['files'].length, 2);
expect(serialized['files']['some id']['fileType'], 'image');
expect(serialized['files']['some id 2']['fileType'], 'apk');
});
test('should serialize in mime mode', () {
const dto = PrepareUploadRequestDto(
info: info,
files: {
'some id': FileDto(
id: 'some id',
fileName: 'another image.jpg',
size: 1234,
fileType: FileType.image,
hash: '*hash*',
preview: '*preview data*',
legacy: false,
),
'some id 2': FileDto(
id: 'some id 2',
fileName: 'my apk.apk',
size: 1234,
fileType: FileType.apk,
hash: '*hash*',
preview: '*preview data*',
legacy: false,
),
},
);
final serialized = dto.toJson();
expect(serialized['info']['deviceType'], 'mobile');
expect(serialized['files'].length, 2);
expect(serialized['files']['some id']['fileType'], 'image/jpeg');
expect(serialized['files']['some id 2']['fileType'], 'application/vnd.android.package-archive');
});
});
test('PrepareUploadResponseDto', () {
final parsed = PrepareUploadResponseDto.fromJson({
'sessionId': 'some session id',
'files': {
'some id': 'some url',
'some id 2': 'some url 2',
},
});
expect(parsed.sessionId, 'some session id');
expect(parsed.files.length, 2);
expect(parsed.files['some id'], 'some url');
expect(parsed.files['some id 2'], 'some url 2');
});
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/util/api_route_builder_test.dart | import 'package:common/common.dart';
import 'package:localsend_app/util/api_route_builder.dart';
import 'package:test/test.dart';
void main() {
group('ApiRoute server urls', () {
test('register', () {
expect(ApiRoute.register.v1, '/api/localsend/v1/register');
expect(ApiRoute.register.v2, '/api/localsend/v2/register');
});
test('prepareUpload', () {
expect(ApiRoute.prepareUpload.v1, '/api/localsend/v1/send-request');
expect(ApiRoute.prepareUpload.v2, '/api/localsend/v2/prepare-upload');
});
});
group('ApiRoute typed client urls', () {
test('register', () {
expect(ApiRoute.register.target(_target(version: '1.0', https: false)), 'http://0.0.0.0:8080/api/localsend/v1/register');
expect(ApiRoute.register.target(_target(version: '1.0', https: true)), 'https://0.0.0.0:8080/api/localsend/v1/register');
expect(ApiRoute.register.target(_target(version: '2.0', https: false)), 'http://0.0.0.0:8080/api/localsend/v2/register');
expect(ApiRoute.register.target(_target(version: '2.0', https: true)), 'https://0.0.0.0:8080/api/localsend/v2/register');
});
test('prepareUpload', () {
expect(ApiRoute.prepareUpload.target(_target(version: '1.0', https: false)), 'http://0.0.0.0:8080/api/localsend/v1/send-request');
expect(ApiRoute.prepareUpload.target(_target(version: '1.0', https: true)), 'https://0.0.0.0:8080/api/localsend/v1/send-request');
expect(ApiRoute.prepareUpload.target(_target(version: '2.0', https: false)), 'http://0.0.0.0:8080/api/localsend/v2/prepare-upload');
expect(ApiRoute.prepareUpload.target(_target(version: '2.0', https: true)), 'https://0.0.0.0:8080/api/localsend/v2/prepare-upload');
});
});
group('ApiRoute raw client urls', () {
test('register', () {
expect(ApiRoute.register.targetRaw('0.0.0.0', 8080, false, '1.0'), 'http://0.0.0.0:8080/api/localsend/v1/register');
expect(ApiRoute.register.targetRaw('0.0.0.0', 8080, true, '1.0'), 'https://0.0.0.0:8080/api/localsend/v1/register');
expect(ApiRoute.register.targetRaw('0.0.0.0', 8080, false, '2.0'), 'http://0.0.0.0:8080/api/localsend/v2/register');
expect(ApiRoute.register.targetRaw('0.0.0.0', 8080, true, '2.0'), 'https://0.0.0.0:8080/api/localsend/v2/register');
});
});
}
Device _target({
required String version,
required bool https,
}) {
return Device(
ip: '0.0.0.0',
version: version,
port: 8080,
https: https,
fingerprint: 'fingerprint',
alias: 'alias',
deviceModel: 'deviceModel',
deviceType: DeviceType.desktop,
download: false,
);
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/util/task_runner_test.dart | import 'package:localsend_app/util/sleep.dart';
import 'package:localsend_app/util/task_runner.dart';
import 'package:test/test.dart';
void main() {
group('TaskRunner', () {
test('should run all tasks in parallel', () async {
final results = TaskRunner<String?>(
concurrency: 10,
initialTasks: [
for (final data in [
[10, null],
[30, 'a'],
[20, 'b'],
[40, 'c']
])
() async {
final delay = data[0] as int;
final result = data[1] as String?;
await sleepAsync(delay);
return result;
},
],
).stream;
String? finalResult;
await results.forEach((result) {
if (finalResult == null && result != null) {
finalResult = result;
}
});
expect(finalResult, 'b');
});
});
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/util/security_helper_test.dart | import 'package:basic_utils/basic_utils.dart';
import 'package:localsend_app/util/security_helper.dart';
import 'package:test/test.dart';
void main() {
group('generateSecurityContext', () {
// certificate is dependent on time, so we skip this test
test('should generate a security context', () {
const modulus =
'17655370025740741038113156454854199388193503449104440877037318492305460691763108986359629213738068251658702764711191809795804339624629386590749322066892437190139062703234048708020881575102122778994526543290880868262952627726488977960776519938694907994518427540419624537894956809241753063372413058294447378662255052300193831939738828105579615087656442141880311261067266950751778487270744852541404898857201772242498437323791185553734672978477936608290952211534467577849886694581791190994405933665028620559373744808123499229584489594678456882464781972729864955090923226165749030219906764402228914184366893373631422503021';
const privateExponent =
'14421008176265737041842552728760854897987189421761902811979258986703749275840685218255600827633436556136869519473805770330945910011841184271318521744401163544644005150782334580299156378790480712915696482733480991790654395453357362699213084041660086971551428119477591606848878236042545176547425781216107887562053872086603693550866169434312772263069345523523039280590638079481520003143359443743141464111595442124530326974852967024986370324441963907065113439224776888067662971143404975436160178871895218249902778285379960904695389191962540588337134680308483675532942364276364403564632886857709821444086544738315317174145';
const privateP =
'178524065934350447993678840182944627942309006340524319909851831752106332954026000610471033106817833873729348468467401050633468292518369706764968836071362023882930741070266054692417392199462715540565991951570137107225695543150432250384310373010291328019775467135529294964213555809388513634733256540639643918349';
const privateQ =
'98896302486373120089171491460892017227056533661820429564718404666288200233919205658787592871460875274200632466484814562010402123837563042503616158962868253836369412258319855713924996179145010239261725685588005640861685432715579085801665010203646507394652948031357507454692937609788924433344012456182622364129';
const publicExponent = '65537';
final keyPair = AsymmetricKeyPair(
RSAPublicKey(
BigInt.parse(modulus),
BigInt.parse(publicExponent),
),
RSAPrivateKey(
BigInt.parse(modulus),
BigInt.parse(privateExponent),
BigInt.parse(privateP),
BigInt.parse(privateQ),
),
);
final context = generateSecurityContext(keyPair);
expect(
context.privateKey,
'''-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAi9uDMYRn63SZtEPGRogZGdu5XXBAoQeMO60mycoinqLKDWyZ
dpMo+XWY3wYVhoAyxgzDOcPjIf+Uq1oEy/0K4WwfpbK8SCy851qgYkfMCT9D9mFv
XwWoULJCUHFF7f947ArDE1nmuK1nNx2RodN2wJCXyzPjw0jn06bwGeg0EqfUC8wv
W4FTZ6t1tErzmRqRdMUWuCJwsk1IMbDbFePhiK5jecOBG0RVVWLuw+TkuX8TUgrp
IktH2+qEM1KdLyAMnL71hx2wMvE+lDKFKK9p37zXK8omjl+VgTC8ocjGeYDDsl43
ZtW09V0pb7Vz2FM8b7BgM06kvJl48PIe5puYbQIDAQABAoIBAHI8hAW/TA7j9+Rp
c5wK8M3RTrCGzxN5Ec9w2Hz80ZhYCcg7S4KyI0bYCl0pIA3zywVASXp2iaEsnSf1
aHOipe+JHLSAsRAXEtm6icSdNojbF005OvoXqer4H/iK/X6wLPpItByrUyzH3sYD
LgBLtPUHZiWBpenONCYKdpYCt/3/uyAeC4qj+sBlfN5Fio2A86qIgntg3n6he8Cd
Yq0cjyEGzRnIa9EUDHoHUU30oPPj16LkK0uZxR7H+UKZkYNXQUGtPt0cnAvgS/2f
UnOAIZop1r9NkS7sntg4l9iuDqI4xYMg9wtBStrgLx65nV1l4HDNZGq/LDo3msam
NQoeX4ECgYEA/joJk42iTF3D2IJjFzMf539V9D/1OaXcxmiLMODsIW8ZcyKRRmzD
NIBfMxX/0+X8IgkMwkcnZWOFMWw+2FDgfz2l+PMACJvGEGokxFDiJe68W4KAy8dr
uB0M0ydhRWLG4ZD6U+gvwyqqlMNpEosCH0fJilag+tW/fx6ti2MBYA0CgYEAjNVA
HItnlpnOmzOuyQob9kqE/8eDTSeX5ZFD/OZOypvLPukdg6qWnzaBzUgSJg/Tl9RD
XWE9WgKc2Gpki7/EYvtRW4YwBcoZKBTkAio4t8WBRmLT6L3PUKKdJHOtFbmwlUPw
mfw9HdJG/TgDiTlyAdTbuGhGY/unuUdPMvt2oeECgYEApthqHoeOo3XKKZbw93Hb
F3AvdhxfkVT0ftZvu0VyU0L5veFK3KBWwGcbk4h1nJjMj33G/N370gOtj1EOMaNq
ordP7QF13TB2naE7vgejU+fJgHk2lAauAGg4WX/3y7TW94TRdS3l4r1mtDlHBR9r
5iGT+JGAFv8fLYtxtA/nACUCgYAb6Gpi/bESY/pQQSaiyjEOVmgSs7uuP2lXYbkC
VbVJayQUnGdv3w8oD8obHuwRxNMeZD7RM2LQAnKIZFT2aJMHNlxB8c50Zz8i9TjV
wP4qVKYwh4cMuQhrJz5SqeWjx39ZpPP538VQsonExiPVPp/8Au1jlq5UQ9tR2PK1
3KT+oQKBgQCkmNd8ZHKBoIbG3oV0T4f4IFk8424QD5hQX7Zmb7gxwnCgQScOPBM/
tk4v/rwNoiO9EUW4w4zZZIlvcFJu38+9pPX+rTFxGh6TZ6aRvw7962m2RBmqgYcq
IWwwBbDLI6KuU/iqqvk/1syLDHqeaCdDqTmmyoaKKa7kUhkZkhIlLw==
-----END RSA PRIVATE KEY-----''',
);
expect(
context.publicKey,
'''-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAi9uDMYRn63SZtEPGRogZGdu5XXBAoQeMO60mycoinqLKDWyZdpMo
+XWY3wYVhoAyxgzDOcPjIf+Uq1oEy/0K4WwfpbK8SCy851qgYkfMCT9D9mFvXwWo
ULJCUHFF7f947ArDE1nmuK1nNx2RodN2wJCXyzPjw0jn06bwGeg0EqfUC8wvW4FT
Z6t1tErzmRqRdMUWuCJwsk1IMbDbFePhiK5jecOBG0RVVWLuw+TkuX8TUgrpIktH
2+qEM1KdLyAMnL71hx2wMvE+lDKFKK9p37zXK8omjl+VgTC8ocjGeYDDsl43ZtW0
9V0pb7Vz2FM8b7BgM06kvJl48PIe5puYbQIDAQAB
-----END RSA PUBLIC KEY-----''',
);
});
});
group('calculateHashOfCertificate', () {
test('should calculate hash of certificate', () {
const certificate = '''-----BEGIN CERTIFICATE-----
MIIDGTCCAgGgAwIBAgIBATANBgkqhkiG9w0BAQsFADBQMRcwFQYDVQQDEw5Mb2Nh
bFNlbmQgVXNlcjEJMAcGA1UEChMAMQkwBwYDVQQLEwAxCTAHBgNVBAcTADEJMAcG
A1UECBMAMQkwBwYDVQQGEwAwHhcNMjMwNDIxMjM0NTM3WhcNMzMwNDE4MjM0NTM3
WjBQMRcwFQYDVQQDEw5Mb2NhbFNlbmQgVXNlcjEJMAcGA1UEChMAMQkwBwYDVQQL
EwAxCTAHBgNVBAcTADEJMAcGA1UECBMAMQkwBwYDVQQGEwAwggEiMA0GCSqGSIb3
DQEBAQUAA4IBDwAwggEKAoIBAQCL24MxhGfrdJm0Q8ZGiBkZ27ldcEChB4w7rSbJ
yiKeosoNbJl2kyj5dZjfBhWGgDLGDMM5w+Mh/5SrWgTL/QrhbB+lsrxILLznWqBi
R8wJP0P2YW9fBahQskJQcUXt/3jsCsMTWea4rWc3HZGh03bAkJfLM+PDSOfTpvAZ
6DQSp9QLzC9bgVNnq3W0SvOZGpF0xRa4InCyTUgxsNsV4+GIrmN5w4EbRFVVYu7D
5OS5fxNSCukiS0fb6oQzUp0vIAycvvWHHbAy8T6UMoUor2nfvNcryiaOX5WBMLyh
yMZ5gMOyXjdm1bT1XSlvtXPYUzxvsGAzTqS8mXjw8h7mm5htAgMBAAEwDQYJKoZI
hvcNAQELBQADggEBAIs+T8Nkbl0gecT22CKW9/jMvUS1PGAyMqlwP8fNTsyv2xE9
hLsyUrxsscuv+HGJu6Cz1R3hLI8YY5jEShmaelI0stlLahH9Fbm43EZuadGXOVKZ
gMrNzQqLY5lec55rmS17GJlkm5opidkq4OlsCHfrBJitX6071atb0B1cdAjysWwV
x40mnwq0TmYgBLDhWaM4/ZfZQRJQpPCtBJO06Nk7gTPiqJGJU5iEaz1PLvARq69o
bJobSekf9tx3uwOIfioaoQvX0khkZ3ljFuNUpW3IE87OfPnYJQhu5xsTx00wi+Ce
x64ghD4CzRa7wYsOjeb8cUUDMSj030NO9fBGVtA=
-----END CERTIFICATE-----''';
final hash = calculateHashOfCertificate(certificate);
expect(hash, '247E5F7CF21DE14438EAE733E07AC5440593D0612570C7413674130608DF69A9');
});
});
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/provider/favorites_provider_test.dart | import 'package:localsend_app/model/persistence/favorite_device.dart';
import 'package:localsend_app/provider/favorites_provider.dart';
import 'package:mockito/mockito.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:test/test.dart';
import '../../mocks.mocks.dart';
void main() {
late MockPersistenceService persistenceService;
setUp(() {
persistenceService = MockPersistenceService();
});
test('Should add a favorite device', () async {
final service = ReduxNotifier.test(
redux: FavoritesService(persistenceService),
);
expect(service.state, []);
final device = _createDevice('1');
await service.dispatchAsync(AddFavoriteAction(device));
expect(service.state, [device]);
verify(persistenceService.setFavorites([device]));
});
test('Should update a favorite device', () async {
final initialDevice = _createDevice('1', alias: 'A');
final service = ReduxNotifier.test(
redux: FavoritesService(persistenceService),
initialState: [initialDevice],
);
// Sanity check
expect(service.state, [initialDevice]);
expect(service.state.first.alias, 'A');
final updatedDevice = _createDevice('1', alias: 'B');
await service.dispatchAsync(UpdateFavoriteAction(updatedDevice));
expect(service.state, [updatedDevice]);
expect(service.state.first.alias, 'B');
verify(persistenceService.setFavorites([updatedDevice]));
});
test('Should not update a favorite device if unknown id', () async {
final initialDevice = _createDevice('1', alias: 'A');
final service = ReduxNotifier.test(
redux: FavoritesService(persistenceService),
initialState: [initialDevice],
);
// Sanity check
expect(service.state, [initialDevice]);
expect(service.state.first.alias, 'A');
final updatedDevice = _createDevice('2', alias: 'B');
await service.dispatchAsync(UpdateFavoriteAction(updatedDevice));
expect(service.state, [initialDevice]);
expect(service.state.first.alias, 'A');
verifyNever(persistenceService.setFavorites(any));
});
test('Should delete favorite device', () async {
final initialDevice = _createDevice('1', fingerprint: '111');
final service = ReduxNotifier.test(
redux: FavoritesService(persistenceService),
initialState: [initialDevice],
);
// Sanity check
expect(service.state, [initialDevice]);
await service.dispatchAsync(RemoveFavoriteAction(deviceFingerprint: '111'));
expect(service.state, []);
verify(persistenceService.setFavorites([]));
});
test('Should not delete favorite device if unknown fingerprint', () async {
final initialDevice = _createDevice('1', fingerprint: '111');
final service = ReduxNotifier.test(
redux: FavoritesService(persistenceService),
initialState: [initialDevice],
);
// Sanity check
expect(service.state, [initialDevice]);
await service.dispatchAsync(RemoveFavoriteAction(deviceFingerprint: '222'));
expect(service.state, [initialDevice]);
verifyNever(persistenceService.setFavorites(any));
});
}
FavoriteDevice _createDevice(
String id, {
String fingerprint = '123',
String alias = 'A',
}) {
return FavoriteDevice(
id: id,
fingerprint: fingerprint,
ip: '1.2.3.4',
port: 123,
alias: alias,
);
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/provider/network_info_provider_test.dart | import 'package:localsend_app/provider/local_ip_provider.dart';
import 'package:test/test.dart';
void main() {
group('rankIpAddresses', () {
test('should only sort list if no primary', () {
expect(rankIpAddresses(['123.456', '222.1', '321.222'], null), ['123.456', '321.222', '222.1']);
});
test('should only take primary', () {
expect(rankIpAddresses([], '123.123'), ['123.123']);
});
test('should sort primary first', () {
expect(rankIpAddresses(['123.456', '222.1', '321.222'], '123.123'), ['123.123', '123.456', '321.222', '222.1']);
});
test('should sort primary first and remove duplicates', () {
expect(rankIpAddresses(['123.456', '123.123', '222.1', '222.1', '321.222'], '123.123'), ['123.123', '123.456', '321.222', '222.1']);
});
});
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/provider/receive_history_provider_test.dart | import 'package:common/common.dart';
import 'package:localsend_app/model/persistence/receive_history_entry.dart';
import 'package:localsend_app/provider/receive_history_provider.dart';
import 'package:mockito/mockito.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:test/test.dart';
import '../../mocks.mocks.dart';
void main() {
late MockPersistenceService persistenceService;
setUp(() {
persistenceService = MockPersistenceService();
when(persistenceService.isSaveToHistory()).thenReturn(true);
});
test('Should add an entry', () async {
final service = ReduxNotifier.test(
redux: ReceiveHistoryService(persistenceService),
);
final entry = _createEntry('1');
await service.dispatchAsync(AddHistoryEntryAction(
entryId: entry.id,
fileName: entry.fileName,
fileType: entry.fileType,
path: entry.path,
savedToGallery: entry.savedToGallery,
fileSize: entry.fileSize,
senderAlias: entry.senderAlias,
timestamp: entry.timestamp,
));
expect(service.state, [entry]);
verify(persistenceService.setReceiveHistory([entry]));
});
test('Should not add an entry if disabled', () async {
when(persistenceService.isSaveToHistory()).thenReturn(false);
final service = ReduxNotifier.test(
redux: ReceiveHistoryService(persistenceService),
);
final entry = _createEntry('1');
await service.dispatchAsync(AddHistoryEntryAction(
entryId: entry.id,
fileName: entry.fileName,
fileType: entry.fileType,
path: entry.path,
savedToGallery: entry.savedToGallery,
fileSize: entry.fileSize,
senderAlias: entry.senderAlias,
timestamp: entry.timestamp,
));
expect(service.state, []);
verifyNever(persistenceService.setReceiveHistory(any));
});
test('Should remove the 200th entry when adding another', () async {
final service = ReduxNotifier.test(
redux: ReceiveHistoryService(persistenceService),
initialState: List.generate(200, (index) => _createEntry(index.toString())),
);
expect(service.state.length, 200);
expect(service.state.first, _createEntry('0'));
expect(service.state.last, _createEntry('199'));
final entry = _createEntry('AAA');
await service.dispatchAsync(AddHistoryEntryAction(
entryId: entry.id,
fileName: entry.fileName,
fileType: entry.fileType,
path: entry.path,
savedToGallery: entry.savedToGallery,
fileSize: entry.fileSize,
senderAlias: entry.senderAlias,
timestamp: entry.timestamp,
));
expect(service.state.length, 200);
expect(service.state.first, entry);
expect(service.state[1], _createEntry('0'));
expect(service.state.last, _createEntry('198'));
});
test('Should remove an entry', () async {
final service = ReduxNotifier.test(
redux: ReceiveHistoryService(persistenceService),
initialState: [
_createEntry('1'),
_createEntry('2'),
_createEntry('3'),
],
);
expect(service.state.length, 3);
await service.dispatchAsync(RemoveHistoryEntryAction('2'));
expect(service.state.length, 2);
expect(service.state, [
_createEntry('1'),
_createEntry('3'),
]);
verify(persistenceService.setReceiveHistory([
_createEntry('1'),
_createEntry('3'),
]));
});
test('Should not remove an entry if not found', () async {
final service = ReduxNotifier.test(
redux: ReceiveHistoryService(persistenceService),
initialState: [
_createEntry('1'),
_createEntry('2'),
_createEntry('3'),
],
);
expect(service.state.length, 3);
await service.dispatchAsync(RemoveHistoryEntryAction('4'));
expect(service.state.length, 3);
expect(service.state, [
_createEntry('1'),
_createEntry('2'),
_createEntry('3'),
]);
verifyNever(persistenceService.setReceiveHistory(any));
});
test('Should remove all entries', () async {
final service = ReduxNotifier.test(
redux: ReceiveHistoryService(persistenceService),
initialState: [
_createEntry('1'),
_createEntry('2'),
_createEntry('3'),
],
);
expect(service.state.length, 3);
await service.dispatchAsync(RemoveAllHistoryEntriesAction());
expect(service.state.length, 0);
verify(persistenceService.setReceiveHistory([]));
});
}
ReceiveHistoryEntry _createEntry(String id) {
return ReceiveHistoryEntry(
id: id,
fileName: 'fileName',
fileType: FileType.image,
path: 'path',
savedToGallery: true,
fileSize: 123,
senderAlias: 'senderAlias',
timestamp: DateTime(2021, 1, 1),
);
}
| 0 |
mirrored_repositories/localsend/app/test/unit | mirrored_repositories/localsend/app/test/unit/provider/last_devices_provider_test.dart | import 'package:common/common.dart';
import 'package:localsend_app/provider/last_devices.provider.dart';
import 'package:refena_flutter/refena_flutter.dart';
import 'package:test/test.dart';
void main() {
test('Should add a device', () {
final service = ReduxNotifier.test(
redux: LastDevicesService(),
);
expect(service.state, []);
final device = _createDevice('123.123');
service.dispatch(AddLastDeviceAction(device));
expect(service.state, [device]);
});
test('Should remove the 5th device', () {
final service = ReduxNotifier.test(
redux: LastDevicesService(),
);
service.dispatch(AddLastDeviceAction(_createDevice('1')));
service.dispatch(AddLastDeviceAction(_createDevice('2')));
service.dispatch(AddLastDeviceAction(_createDevice('3')));
service.dispatch(AddLastDeviceAction(_createDevice('4')));
service.dispatch(AddLastDeviceAction(_createDevice('5')));
expect(service.state.length, 5);
expect(service.state, [
_createDevice('5'),
_createDevice('4'),
_createDevice('3'),
_createDevice('2'),
_createDevice('1'),
]);
service.dispatch(AddLastDeviceAction(_createDevice('6')));
expect(service.state.length, 5);
expect(service.state, [
_createDevice('6'),
_createDevice('5'),
_createDevice('4'),
_createDevice('3'),
_createDevice('2'), // 5th device removed
]);
});
}
Device _createDevice(String ip) {
return Device(
ip: ip,
version: '1',
port: 123,
https: true,
fingerprint: '123',
alias: 'A',
deviceModel: 'A',
deviceType: DeviceType.mobile,
download: false,
);
}
| 0 |
mirrored_repositories/localsend | mirrored_repositories/localsend/scripts/contributions_digester.dart | import 'dart:io';
/// Used to make the changes in the Github Releases shorter.
/// Aggregates documentation and i18n PRs to "i18n: @user1, @user2".
/// Keeps other contributions (PRs) as is.
void main() {
final contributions = File('contributions.txt').readAsLinesSync();
final newContributions = <String>[];
final documentations = <String>{}; // list of "@user"
final translators = <String>{}; // list of "@user"
for (String pr in contributions) {
final originalPr = pr;
pr = pr.toLowerCase();
if (pr.contains('@dependabot')) {
continue;
}
if (pr.contains('i18n') || pr.contains('translation') || pr.contains('translator') || pr.contains('translate') || pr.contains('language')) {
translators.add('@' + originalPr.split(' @').last);
} else if (pr.contains('readme') || pr.contains('contributing')) {
documentations.add('@' + originalPr.split(' @').last);
} else {
newContributions.add(originalPr);
}
}
final content = newContributions.join('\n') + '\n' + '* docs: ${documentations.join(', ')}' + '\n' + '* i18n: ${translators.join(', ')}';
print('Content: $content');
File('contributions_digested.txt').writeAsStringSync(content);
print('Finish!');
}
| 0 |
mirrored_repositories/localsend/common | mirrored_repositories/localsend/common/lib/common.dart | export 'package:common/src/constants.dart';
export 'package:common/src/model/device.dart';
export 'package:common/src/model/dto/file_dto.dart';
export 'package:common/src/model/dto/info_dto.dart';
export 'package:common/src/model/dto/info_register_dto.dart';
export 'package:common/src/model/dto/multicast_dto.dart';
export 'package:common/src/model/dto/prepare_upload_request_dto.dart';
export 'package:common/src/model/dto/prepare_upload_response_dto.dart';
export 'package:common/src/model/dto/receive_request_response_dto.dart';
export 'package:common/src/model/dto/register_dto.dart';
export 'package:common/src/model/file_status.dart';
export 'package:common/src/model/file_type.dart';
export 'package:common/src/model/session_status.dart';
export 'package:common/src/model/stored_security_context.dart';
| 0 |
mirrored_repositories/localsend/common/lib | mirrored_repositories/localsend/common/lib/src/isolate_parent_controller.dart | import 'package:common/src/isolate_child_controller.dart';
import 'package:common/src/model/state/isolate_common_state.dart';
import 'package:common/src/model/state/isolate_parent_state.dart';
import 'package:common/src/model/state/isolate_ref_state.dart';
import 'package:common/src/model/state/isolate_state.dart';
import 'package:common/src/model/state/isolate_sync_dto.dart';
import 'package:common/src/model/stored_security_context.dart';
import 'package:common/src/util/id_provider.dart';
import 'package:common/src/util/isolate_helper.dart';
import 'package:refena/refena.dart';
final _idProvider = IdProvider();
final isolateParentProvider = ReduxProvider<IsolateParentController, IsolateParentState>((ref) {
return IsolateParentController();
});
class IsolateParentController extends ReduxNotifier<IsolateParentState> {
@override
IsolateParentState init() => IsolateParentState(
commonState: IsolateCommonState(
securityContext: null,
),
isolateStates: {},
);
}
/// Starts the required isolates.
/// Should be called by the main isolate.
class IsolateSetupAction extends AsyncReduxAction<IsolateParentController, IsolateParentState> {
@override
Future<IsolateParentState> reduce() async {
final isolateId = _idProvider.getNextId();
final isolateState = IsolateState(
isolateId: isolateId,
isolateType: IsolateType.multicast,
);
final initialData = IsolateSyncDto(
isolateState: isolateState,
isolateCommonState: state.commonState,
);
final communication = await startIsolate<Object, IsolateSyncDto, IsolateSyncDto>(
task: setupChildIsolate,
param: initialData,
);
return state.copyWith(
isolateStates: {
isolateId: IsolateRefState(
communication: communication,
isolateState: isolateState,
),
},
);
}
}
/// Publishes the new security context to all isolates.
class IsolateSyncSecurityContextAction extends ReduxAction<IsolateParentController, IsolateParentState> {
final StoredSecurityContext securityContext;
IsolateSyncSecurityContextAction({
required this.securityContext,
});
@override
IsolateParentState reduce() {
final commonState = state.commonState.copyWith(
securityContext: securityContext,
);
for (final isolateState in state.isolateStates.values) {
isolateState.communication.sendToIsolate(IsolateSyncDto(
isolateState: isolateState.isolateState,
isolateCommonState: commonState,
));
}
return state.copyWith(
commonState: commonState,
);
}
}
| 0 |
mirrored_repositories/localsend/common/lib | mirrored_repositories/localsend/common/lib/src/constants.dart | /// The protocol version.
///
/// Version table:
/// Protocols | App (Official implementation)
/// ----------|------------------------------
/// 1.0 | 1.0.0 - 1.8.0
/// 1.0, 2.0 | 1.9.0
const protocolVersion = '2.0';
/// Assumed protocol version of peers for first handshake.
/// Generally this should be slightly lower than the current protocol version.
const peerProtocolVersion = '1.0';
/// The protocol version when no version is specified.
/// Prior v2, the protocol version was not specified.
const fallbackProtocolVersion = '1.0';
/// The default http server port and
/// and multicast port.
const defaultPort = 53317;
/// The default multicast group should be 224.0.0.0/24
/// because on some Android devices this is the only IP range
/// that can receive UDP multicast messages.
const defaultMulticastGroup = '224.0.0.167';
| 0 |
mirrored_repositories/localsend/common/lib | mirrored_repositories/localsend/common/lib/src/isolate_child_controller.dart | import 'package:common/src/model/state/isolate_child_state.dart';
import 'package:common/src/model/state/isolate_sync_dto.dart';
import 'package:meta/meta.dart';
import 'package:refena/refena.dart';
@internal
final isolateContainer = RefenaContainer();
/// Contains the state of the child isolate.
final isolateChildProvider = ReduxProvider<IsolateChildController, IsolateChildState>((ref) {
throw 'Not initialized';
});
class IsolateChildController extends ReduxNotifier<IsolateChildState> {
final IsolateChildState initialState;
IsolateChildController({
required this.initialState,
});
@override
IsolateChildState init() => initialState;
}
@internal
Future<void> setupChildIsolate(
Stream<IsolateSyncDto> receiveFromMain,
void Function(Object) sendToMain,
IsolateSyncDto? initialData,
) async {
final commonState = initialData!.isolateCommonState;
final isolateState = initialData.isolateState;
isolateContainer.set(
isolateChildProvider.overrideWithNotifier(
(ref) => IsolateChildController(
initialState: IsolateChildState(
commonState: commonState,
isolateState: isolateState,
),
),
),
);
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/stored_security_context.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'stored_security_context.mapper.dart';
@MappableClass()
class StoredSecurityContext with StoredSecurityContextMappable {
final String privateKey;
final String publicKey;
final String certificate;
final String certificateHash;
const StoredSecurityContext({
required this.privateKey,
required this.publicKey,
required this.certificate,
required this.certificateHash,
});
static const fromJson = StoredSecurityContextMapper.fromJson;
@override
String toString() {
return 'StoredSecurityContext(<privateKey>, <publicKey>, <certificate>, <certificateHash>)';
}
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/file_status.dart | /// Status of one single file during file transfer.
/// Both receiver and sender should share the same information.
enum FileStatus {
queue,
skipped,
sending,
failed,
finished,
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/file_type.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'file_type.dart';
class FileTypeMapper extends EnumMapper<FileType> {
FileTypeMapper._();
static FileTypeMapper? _instance;
static FileTypeMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = FileTypeMapper._());
}
return _instance!;
}
static FileType fromValue(dynamic value) {
ensureInitialized();
return MapperContainer.globals.fromValue(value);
}
@override
FileType decode(dynamic value) {
switch (value) {
case 'image':
return FileType.image;
case 'video':
return FileType.video;
case 'pdf':
return FileType.pdf;
case 'text':
return FileType.text;
case 'apk':
return FileType.apk;
case 'other':
return FileType.other;
default:
return FileType.values[5];
}
}
@override
dynamic encode(FileType self) {
switch (self) {
case FileType.image:
return 'image';
case FileType.video:
return 'video';
case FileType.pdf:
return 'pdf';
case FileType.text:
return 'text';
case FileType.apk:
return 'apk';
case FileType.other:
return 'other';
}
}
}
extension FileTypeMapperExtension on FileType {
String toValue() {
FileTypeMapper.ensureInitialized();
return MapperContainer.globals.toValue<FileType>(this) as String;
}
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/device.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'device.dart';
class DeviceTypeMapper extends EnumMapper<DeviceType> {
DeviceTypeMapper._();
static DeviceTypeMapper? _instance;
static DeviceTypeMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = DeviceTypeMapper._());
}
return _instance!;
}
static DeviceType fromValue(dynamic value) {
ensureInitialized();
return MapperContainer.globals.fromValue(value);
}
@override
DeviceType decode(dynamic value) {
switch (value) {
case 'mobile':
return DeviceType.mobile;
case 'desktop':
return DeviceType.desktop;
case 'web':
return DeviceType.web;
case 'headless':
return DeviceType.headless;
case 'server':
return DeviceType.server;
default:
return DeviceType.values[1];
}
}
@override
dynamic encode(DeviceType self) {
switch (self) {
case DeviceType.mobile:
return 'mobile';
case DeviceType.desktop:
return 'desktop';
case DeviceType.web:
return 'web';
case DeviceType.headless:
return 'headless';
case DeviceType.server:
return 'server';
}
}
}
extension DeviceTypeMapperExtension on DeviceType {
String toValue() {
DeviceTypeMapper.ensureInitialized();
return MapperContainer.globals.toValue<DeviceType>(this) as String;
}
}
class DeviceMapper extends ClassMapperBase<Device> {
DeviceMapper._();
static DeviceMapper? _instance;
static DeviceMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = DeviceMapper._());
DeviceTypeMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'Device';
static String _$ip(Device v) => v.ip;
static const Field<Device, String> _f$ip = Field('ip', _$ip);
static String _$version(Device v) => v.version;
static const Field<Device, String> _f$version = Field('version', _$version);
static int _$port(Device v) => v.port;
static const Field<Device, int> _f$port = Field('port', _$port);
static bool _$https(Device v) => v.https;
static const Field<Device, bool> _f$https = Field('https', _$https);
static String _$fingerprint(Device v) => v.fingerprint;
static const Field<Device, String> _f$fingerprint =
Field('fingerprint', _$fingerprint);
static String _$alias(Device v) => v.alias;
static const Field<Device, String> _f$alias = Field('alias', _$alias);
static String? _$deviceModel(Device v) => v.deviceModel;
static const Field<Device, String> _f$deviceModel =
Field('deviceModel', _$deviceModel);
static DeviceType _$deviceType(Device v) => v.deviceType;
static const Field<Device, DeviceType> _f$deviceType =
Field('deviceType', _$deviceType);
static bool _$download(Device v) => v.download;
static const Field<Device, bool> _f$download = Field('download', _$download);
@override
final Map<Symbol, Field<Device, dynamic>> fields = const {
#ip: _f$ip,
#version: _f$version,
#port: _f$port,
#https: _f$https,
#fingerprint: _f$fingerprint,
#alias: _f$alias,
#deviceModel: _f$deviceModel,
#deviceType: _f$deviceType,
#download: _f$download,
};
static Device _instantiate(DecodingData data) {
return Device(
ip: data.dec(_f$ip),
version: data.dec(_f$version),
port: data.dec(_f$port),
https: data.dec(_f$https),
fingerprint: data.dec(_f$fingerprint),
alias: data.dec(_f$alias),
deviceModel: data.dec(_f$deviceModel),
deviceType: data.dec(_f$deviceType),
download: data.dec(_f$download));
}
@override
final Function instantiate = _instantiate;
static Device fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<Device>(map);
}
static Device deserialize(String json) {
return ensureInitialized().decodeJson<Device>(json);
}
}
mixin DeviceMappable {
String serialize() {
return DeviceMapper.ensureInitialized().encodeJson<Device>(this as Device);
}
Map<String, dynamic> toJson() {
return DeviceMapper.ensureInitialized().encodeMap<Device>(this as Device);
}
DeviceCopyWith<Device, Device, Device> get copyWith =>
_DeviceCopyWithImpl(this as Device, $identity, $identity);
@override
String toString() {
return DeviceMapper.ensureInitialized().stringifyValue(this as Device);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
DeviceMapper.ensureInitialized()
.isValueEqual(this as Device, other));
}
@override
int get hashCode {
return DeviceMapper.ensureInitialized().hashValue(this as Device);
}
}
extension DeviceValueCopy<$R, $Out> on ObjectCopyWith<$R, Device, $Out> {
DeviceCopyWith<$R, Device, $Out> get $asDevice =>
$base.as((v, t, t2) => _DeviceCopyWithImpl(v, t, t2));
}
abstract class DeviceCopyWith<$R, $In extends Device, $Out>
implements ClassCopyWith<$R, $In, $Out> {
$R call(
{String? ip,
String? version,
int? port,
bool? https,
String? fingerprint,
String? alias,
String? deviceModel,
DeviceType? deviceType,
bool? download});
DeviceCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _DeviceCopyWithImpl<$R, $Out> extends ClassCopyWithBase<$R, Device, $Out>
implements DeviceCopyWith<$R, Device, $Out> {
_DeviceCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<Device> $mapper = DeviceMapper.ensureInitialized();
@override
$R call(
{String? ip,
String? version,
int? port,
bool? https,
String? fingerprint,
String? alias,
Object? deviceModel = $none,
DeviceType? deviceType,
bool? download}) =>
$apply(FieldCopyWithData({
if (ip != null) #ip: ip,
if (version != null) #version: version,
if (port != null) #port: port,
if (https != null) #https: https,
if (fingerprint != null) #fingerprint: fingerprint,
if (alias != null) #alias: alias,
if (deviceModel != $none) #deviceModel: deviceModel,
if (deviceType != null) #deviceType: deviceType,
if (download != null) #download: download
}));
@override
Device $make(CopyWithData data) => Device(
ip: data.get(#ip, or: $value.ip),
version: data.get(#version, or: $value.version),
port: data.get(#port, or: $value.port),
https: data.get(#https, or: $value.https),
fingerprint: data.get(#fingerprint, or: $value.fingerprint),
alias: data.get(#alias, or: $value.alias),
deviceModel: data.get(#deviceModel, or: $value.deviceModel),
deviceType: data.get(#deviceType, or: $value.deviceType),
download: data.get(#download, or: $value.download));
@override
DeviceCopyWith<$R2, Device, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_DeviceCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/session_status.dart | /// Status of one file transfer.
/// Both receiver and sender should share the same information.
enum SessionStatus {
waiting, // wait for receiver response (wait for decline / accept)
recipientBusy, // recipient is busy with another request (end of session)
declined, // receiver declined the request (end of session)
sending, // files are being sent
finished, // all files sent (end of session)
finishedWithErrors, // finished but some files could not be sent (end of session)
canceledBySender, // cancellation by sender (end of session)
canceledByReceiver, // cancellation by receiver (end of session)
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/stored_security_context.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'stored_security_context.dart';
class StoredSecurityContextMapper
extends ClassMapperBase<StoredSecurityContext> {
StoredSecurityContextMapper._();
static StoredSecurityContextMapper? _instance;
static StoredSecurityContextMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = StoredSecurityContextMapper._());
}
return _instance!;
}
@override
final String id = 'StoredSecurityContext';
static String _$privateKey(StoredSecurityContext v) => v.privateKey;
static const Field<StoredSecurityContext, String> _f$privateKey =
Field('privateKey', _$privateKey);
static String _$publicKey(StoredSecurityContext v) => v.publicKey;
static const Field<StoredSecurityContext, String> _f$publicKey =
Field('publicKey', _$publicKey);
static String _$certificate(StoredSecurityContext v) => v.certificate;
static const Field<StoredSecurityContext, String> _f$certificate =
Field('certificate', _$certificate);
static String _$certificateHash(StoredSecurityContext v) => v.certificateHash;
static const Field<StoredSecurityContext, String> _f$certificateHash =
Field('certificateHash', _$certificateHash);
@override
final Map<Symbol, Field<StoredSecurityContext, dynamic>> fields = const {
#privateKey: _f$privateKey,
#publicKey: _f$publicKey,
#certificate: _f$certificate,
#certificateHash: _f$certificateHash,
};
static StoredSecurityContext _instantiate(DecodingData data) {
return StoredSecurityContext(
privateKey: data.dec(_f$privateKey),
publicKey: data.dec(_f$publicKey),
certificate: data.dec(_f$certificate),
certificateHash: data.dec(_f$certificateHash));
}
@override
final Function instantiate = _instantiate;
static StoredSecurityContext fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<StoredSecurityContext>(map);
}
static StoredSecurityContext deserialize(String json) {
return ensureInitialized().decodeJson<StoredSecurityContext>(json);
}
}
mixin StoredSecurityContextMappable {
String serialize() {
return StoredSecurityContextMapper.ensureInitialized()
.encodeJson<StoredSecurityContext>(this as StoredSecurityContext);
}
Map<String, dynamic> toJson() {
return StoredSecurityContextMapper.ensureInitialized()
.encodeMap<StoredSecurityContext>(this as StoredSecurityContext);
}
StoredSecurityContextCopyWith<StoredSecurityContext, StoredSecurityContext,
StoredSecurityContext>
get copyWith => _StoredSecurityContextCopyWithImpl(
this as StoredSecurityContext, $identity, $identity);
@override
String toString() {
return StoredSecurityContextMapper.ensureInitialized()
.stringifyValue(this as StoredSecurityContext);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
StoredSecurityContextMapper.ensureInitialized()
.isValueEqual(this as StoredSecurityContext, other));
}
@override
int get hashCode {
return StoredSecurityContextMapper.ensureInitialized()
.hashValue(this as StoredSecurityContext);
}
}
extension StoredSecurityContextValueCopy<$R, $Out>
on ObjectCopyWith<$R, StoredSecurityContext, $Out> {
StoredSecurityContextCopyWith<$R, StoredSecurityContext, $Out>
get $asStoredSecurityContext =>
$base.as((v, t, t2) => _StoredSecurityContextCopyWithImpl(v, t, t2));
}
abstract class StoredSecurityContextCopyWith<
$R,
$In extends StoredSecurityContext,
$Out> implements ClassCopyWith<$R, $In, $Out> {
$R call(
{String? privateKey,
String? publicKey,
String? certificate,
String? certificateHash});
StoredSecurityContextCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _StoredSecurityContextCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, StoredSecurityContext, $Out>
implements StoredSecurityContextCopyWith<$R, StoredSecurityContext, $Out> {
_StoredSecurityContextCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<StoredSecurityContext> $mapper =
StoredSecurityContextMapper.ensureInitialized();
@override
$R call(
{String? privateKey,
String? publicKey,
String? certificate,
String? certificateHash}) =>
$apply(FieldCopyWithData({
if (privateKey != null) #privateKey: privateKey,
if (publicKey != null) #publicKey: publicKey,
if (certificate != null) #certificate: certificate,
if (certificateHash != null) #certificateHash: certificateHash
}));
@override
StoredSecurityContext $make(CopyWithData data) => StoredSecurityContext(
privateKey: data.get(#privateKey, or: $value.privateKey),
publicKey: data.get(#publicKey, or: $value.publicKey),
certificate: data.get(#certificate, or: $value.certificate),
certificateHash: data.get(#certificateHash, or: $value.certificateHash));
@override
StoredSecurityContextCopyWith<$R2, StoredSecurityContext, $Out2>
$chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_StoredSecurityContextCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/file_type.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'file_type.mapper.dart';
/// Categorization of one file.
/// We use this information for a better UX.
@MappableEnum(defaultValue: FileType.other)
enum FileType {
image,
video,
pdf,
text,
apk,
other,
}
| 0 |
mirrored_repositories/localsend/common/lib/src | mirrored_repositories/localsend/common/lib/src/model/device.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'device.mapper.dart';
@MappableEnum(defaultValue: DeviceType.desktop)
enum DeviceType {
mobile,
desktop,
web,
headless,
server,
}
/// Internal device model.
/// It gets not serialized.
@MappableClass()
class Device with DeviceMappable {
final String ip;
final String version;
final int port;
final bool https;
final String fingerprint;
final String alias;
final String? deviceModel;
final DeviceType deviceType;
final bool download;
const Device({
required this.ip,
required this.version,
required this.port,
required this.https,
required this.fingerprint,
required this.alias,
required this.deviceModel,
required this.deviceType,
required this.download,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_parent_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'isolate_parent_state.dart';
class IsolateParentStateMapper extends ClassMapperBase<IsolateParentState> {
IsolateParentStateMapper._();
static IsolateParentStateMapper? _instance;
static IsolateParentStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = IsolateParentStateMapper._());
IsolateCommonStateMapper.ensureInitialized();
IsolateRefStateMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'IsolateParentState';
static IsolateCommonState _$commonState(IsolateParentState v) =>
v.commonState;
static const Field<IsolateParentState, IsolateCommonState> _f$commonState =
Field('commonState', _$commonState);
static Map<int, IsolateRefState> _$isolateStates(IsolateParentState v) =>
v.isolateStates;
static const Field<IsolateParentState, Map<int, IsolateRefState>>
_f$isolateStates = Field('isolateStates', _$isolateStates);
@override
final Map<Symbol, Field<IsolateParentState, dynamic>> fields = const {
#commonState: _f$commonState,
#isolateStates: _f$isolateStates,
};
static IsolateParentState _instantiate(DecodingData data) {
return IsolateParentState(
commonState: data.dec(_f$commonState),
isolateStates: data.dec(_f$isolateStates));
}
@override
final Function instantiate = _instantiate;
static IsolateParentState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<IsolateParentState>(map);
}
static IsolateParentState deserialize(String json) {
return ensureInitialized().decodeJson<IsolateParentState>(json);
}
}
mixin IsolateParentStateMappable {
String serialize() {
return IsolateParentStateMapper.ensureInitialized()
.encodeJson<IsolateParentState>(this as IsolateParentState);
}
Map<String, dynamic> toJson() {
return IsolateParentStateMapper.ensureInitialized()
.encodeMap<IsolateParentState>(this as IsolateParentState);
}
IsolateParentStateCopyWith<IsolateParentState, IsolateParentState,
IsolateParentState>
get copyWith => _IsolateParentStateCopyWithImpl(
this as IsolateParentState, $identity, $identity);
@override
String toString() {
return IsolateParentStateMapper.ensureInitialized()
.stringifyValue(this as IsolateParentState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
IsolateParentStateMapper.ensureInitialized()
.isValueEqual(this as IsolateParentState, other));
}
@override
int get hashCode {
return IsolateParentStateMapper.ensureInitialized()
.hashValue(this as IsolateParentState);
}
}
extension IsolateParentStateValueCopy<$R, $Out>
on ObjectCopyWith<$R, IsolateParentState, $Out> {
IsolateParentStateCopyWith<$R, IsolateParentState, $Out>
get $asIsolateParentState =>
$base.as((v, t, t2) => _IsolateParentStateCopyWithImpl(v, t, t2));
}
abstract class IsolateParentStateCopyWith<$R, $In extends IsolateParentState,
$Out> implements ClassCopyWith<$R, $In, $Out> {
IsolateCommonStateCopyWith<$R, IsolateCommonState, IsolateCommonState>
get commonState;
MapCopyWith<$R, int, IsolateRefState,
IsolateRefStateCopyWith<$R, IsolateRefState, IsolateRefState>>
get isolateStates;
$R call(
{IsolateCommonState? commonState,
Map<int, IsolateRefState>? isolateStates});
IsolateParentStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _IsolateParentStateCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, IsolateParentState, $Out>
implements IsolateParentStateCopyWith<$R, IsolateParentState, $Out> {
_IsolateParentStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<IsolateParentState> $mapper =
IsolateParentStateMapper.ensureInitialized();
@override
IsolateCommonStateCopyWith<$R, IsolateCommonState, IsolateCommonState>
get commonState =>
$value.commonState.copyWith.$chain((v) => call(commonState: v));
@override
MapCopyWith<$R, int, IsolateRefState,
IsolateRefStateCopyWith<$R, IsolateRefState, IsolateRefState>>
get isolateStates => MapCopyWith($value.isolateStates,
(v, t) => v.copyWith.$chain(t), (v) => call(isolateStates: v));
@override
$R call(
{IsolateCommonState? commonState,
Map<int, IsolateRefState>? isolateStates}) =>
$apply(FieldCopyWithData({
if (commonState != null) #commonState: commonState,
if (isolateStates != null) #isolateStates: isolateStates
}));
@override
IsolateParentState $make(CopyWithData data) => IsolateParentState(
commonState: data.get(#commonState, or: $value.commonState),
isolateStates: data.get(#isolateStates, or: $value.isolateStates));
@override
IsolateParentStateCopyWith<$R2, IsolateParentState, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_IsolateParentStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_ref_state.dart | import 'package:common/src/model/state/isolate_state.dart';
import 'package:common/src/util/isolate_helper.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'isolate_ref_state.mapper.dart';
/// Contains not only the state of the child isolate but also the communication channel.
/// This state is owned by the parent isolate.
@MappableClass()
class IsolateRefState with IsolateRefStateMappable {
final IsolateCommunication communication;
final IsolateState isolateState;
const IsolateRefState({
required this.communication,
required this.isolateState,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'isolate_state.dart';
class IsolateStateMapper extends ClassMapperBase<IsolateState> {
IsolateStateMapper._();
static IsolateStateMapper? _instance;
static IsolateStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = IsolateStateMapper._());
}
return _instance!;
}
@override
final String id = 'IsolateState';
static int? _$isolateId(IsolateState v) => v.isolateId;
static const Field<IsolateState, int> _f$isolateId =
Field('isolateId', _$isolateId);
static IsolateType? _$isolateType(IsolateState v) => v.isolateType;
static const Field<IsolateState, IsolateType> _f$isolateType =
Field('isolateType', _$isolateType);
@override
final Map<Symbol, Field<IsolateState, dynamic>> fields = const {
#isolateId: _f$isolateId,
#isolateType: _f$isolateType,
};
static IsolateState _instantiate(DecodingData data) {
return IsolateState(
isolateId: data.dec(_f$isolateId),
isolateType: data.dec(_f$isolateType));
}
@override
final Function instantiate = _instantiate;
static IsolateState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<IsolateState>(map);
}
static IsolateState deserialize(String json) {
return ensureInitialized().decodeJson<IsolateState>(json);
}
}
mixin IsolateStateMappable {
String serialize() {
return IsolateStateMapper.ensureInitialized()
.encodeJson<IsolateState>(this as IsolateState);
}
Map<String, dynamic> toJson() {
return IsolateStateMapper.ensureInitialized()
.encodeMap<IsolateState>(this as IsolateState);
}
IsolateStateCopyWith<IsolateState, IsolateState, IsolateState> get copyWith =>
_IsolateStateCopyWithImpl(this as IsolateState, $identity, $identity);
@override
String toString() {
return IsolateStateMapper.ensureInitialized()
.stringifyValue(this as IsolateState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
IsolateStateMapper.ensureInitialized()
.isValueEqual(this as IsolateState, other));
}
@override
int get hashCode {
return IsolateStateMapper.ensureInitialized()
.hashValue(this as IsolateState);
}
}
extension IsolateStateValueCopy<$R, $Out>
on ObjectCopyWith<$R, IsolateState, $Out> {
IsolateStateCopyWith<$R, IsolateState, $Out> get $asIsolateState =>
$base.as((v, t, t2) => _IsolateStateCopyWithImpl(v, t, t2));
}
abstract class IsolateStateCopyWith<$R, $In extends IsolateState, $Out>
implements ClassCopyWith<$R, $In, $Out> {
$R call({int? isolateId, IsolateType? isolateType});
IsolateStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(Then<$Out2, $R2> t);
}
class _IsolateStateCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, IsolateState, $Out>
implements IsolateStateCopyWith<$R, IsolateState, $Out> {
_IsolateStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<IsolateState> $mapper =
IsolateStateMapper.ensureInitialized();
@override
$R call({Object? isolateId = $none, Object? isolateType = $none}) =>
$apply(FieldCopyWithData({
if (isolateId != $none) #isolateId: isolateId,
if (isolateType != $none) #isolateType: isolateType
}));
@override
IsolateState $make(CopyWithData data) => IsolateState(
isolateId: data.get(#isolateId, or: $value.isolateId),
isolateType: data.get(#isolateType, or: $value.isolateType));
@override
IsolateStateCopyWith<$R2, IsolateState, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_IsolateStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_common_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'isolate_common_state.dart';
class IsolateCommonStateMapper extends ClassMapperBase<IsolateCommonState> {
IsolateCommonStateMapper._();
static IsolateCommonStateMapper? _instance;
static IsolateCommonStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = IsolateCommonStateMapper._());
StoredSecurityContextMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'IsolateCommonState';
static StoredSecurityContext? _$securityContext(IsolateCommonState v) =>
v.securityContext;
static const Field<IsolateCommonState, StoredSecurityContext>
_f$securityContext = Field('securityContext', _$securityContext);
@override
final Map<Symbol, Field<IsolateCommonState, dynamic>> fields = const {
#securityContext: _f$securityContext,
};
static IsolateCommonState _instantiate(DecodingData data) {
return IsolateCommonState(securityContext: data.dec(_f$securityContext));
}
@override
final Function instantiate = _instantiate;
static IsolateCommonState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<IsolateCommonState>(map);
}
static IsolateCommonState deserialize(String json) {
return ensureInitialized().decodeJson<IsolateCommonState>(json);
}
}
mixin IsolateCommonStateMappable {
String serialize() {
return IsolateCommonStateMapper.ensureInitialized()
.encodeJson<IsolateCommonState>(this as IsolateCommonState);
}
Map<String, dynamic> toJson() {
return IsolateCommonStateMapper.ensureInitialized()
.encodeMap<IsolateCommonState>(this as IsolateCommonState);
}
IsolateCommonStateCopyWith<IsolateCommonState, IsolateCommonState,
IsolateCommonState>
get copyWith => _IsolateCommonStateCopyWithImpl(
this as IsolateCommonState, $identity, $identity);
@override
String toString() {
return IsolateCommonStateMapper.ensureInitialized()
.stringifyValue(this as IsolateCommonState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
IsolateCommonStateMapper.ensureInitialized()
.isValueEqual(this as IsolateCommonState, other));
}
@override
int get hashCode {
return IsolateCommonStateMapper.ensureInitialized()
.hashValue(this as IsolateCommonState);
}
}
extension IsolateCommonStateValueCopy<$R, $Out>
on ObjectCopyWith<$R, IsolateCommonState, $Out> {
IsolateCommonStateCopyWith<$R, IsolateCommonState, $Out>
get $asIsolateCommonState =>
$base.as((v, t, t2) => _IsolateCommonStateCopyWithImpl(v, t, t2));
}
abstract class IsolateCommonStateCopyWith<$R, $In extends IsolateCommonState,
$Out> implements ClassCopyWith<$R, $In, $Out> {
StoredSecurityContextCopyWith<$R, StoredSecurityContext,
StoredSecurityContext>? get securityContext;
$R call({StoredSecurityContext? securityContext});
IsolateCommonStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _IsolateCommonStateCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, IsolateCommonState, $Out>
implements IsolateCommonStateCopyWith<$R, IsolateCommonState, $Out> {
_IsolateCommonStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<IsolateCommonState> $mapper =
IsolateCommonStateMapper.ensureInitialized();
@override
StoredSecurityContextCopyWith<$R, StoredSecurityContext,
StoredSecurityContext>?
get securityContext => $value.securityContext?.copyWith
.$chain((v) => call(securityContext: v));
@override
$R call({Object? securityContext = $none}) => $apply(FieldCopyWithData(
{if (securityContext != $none) #securityContext: securityContext}));
@override
IsolateCommonState $make(CopyWithData data) => IsolateCommonState(
securityContext: data.get(#securityContext, or: $value.securityContext));
@override
IsolateCommonStateCopyWith<$R2, IsolateCommonState, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_IsolateCommonStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_sync_dto.dart | import 'package:common/src/model/state/isolate_common_state.dart';
import 'package:common/src/model/state/isolate_state.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'isolate_sync_dto.mapper.dart';
@MappableClass()
class IsolateSyncDto with IsolateSyncDtoMappable {
final IsolateState isolateState;
final IsolateCommonState isolateCommonState;
const IsolateSyncDto({
required this.isolateState,
required this.isolateCommonState,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_sync_dto.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'isolate_sync_dto.dart';
class IsolateSyncDtoMapper extends ClassMapperBase<IsolateSyncDto> {
IsolateSyncDtoMapper._();
static IsolateSyncDtoMapper? _instance;
static IsolateSyncDtoMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = IsolateSyncDtoMapper._());
IsolateStateMapper.ensureInitialized();
IsolateCommonStateMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'IsolateSyncDto';
static IsolateState _$isolateState(IsolateSyncDto v) => v.isolateState;
static const Field<IsolateSyncDto, IsolateState> _f$isolateState =
Field('isolateState', _$isolateState);
static IsolateCommonState _$isolateCommonState(IsolateSyncDto v) =>
v.isolateCommonState;
static const Field<IsolateSyncDto, IsolateCommonState> _f$isolateCommonState =
Field('isolateCommonState', _$isolateCommonState);
@override
final Map<Symbol, Field<IsolateSyncDto, dynamic>> fields = const {
#isolateState: _f$isolateState,
#isolateCommonState: _f$isolateCommonState,
};
static IsolateSyncDto _instantiate(DecodingData data) {
return IsolateSyncDto(
isolateState: data.dec(_f$isolateState),
isolateCommonState: data.dec(_f$isolateCommonState));
}
@override
final Function instantiate = _instantiate;
static IsolateSyncDto fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<IsolateSyncDto>(map);
}
static IsolateSyncDto deserialize(String json) {
return ensureInitialized().decodeJson<IsolateSyncDto>(json);
}
}
mixin IsolateSyncDtoMappable {
String serialize() {
return IsolateSyncDtoMapper.ensureInitialized()
.encodeJson<IsolateSyncDto>(this as IsolateSyncDto);
}
Map<String, dynamic> toJson() {
return IsolateSyncDtoMapper.ensureInitialized()
.encodeMap<IsolateSyncDto>(this as IsolateSyncDto);
}
IsolateSyncDtoCopyWith<IsolateSyncDto, IsolateSyncDto, IsolateSyncDto>
get copyWith => _IsolateSyncDtoCopyWithImpl(
this as IsolateSyncDto, $identity, $identity);
@override
String toString() {
return IsolateSyncDtoMapper.ensureInitialized()
.stringifyValue(this as IsolateSyncDto);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
IsolateSyncDtoMapper.ensureInitialized()
.isValueEqual(this as IsolateSyncDto, other));
}
@override
int get hashCode {
return IsolateSyncDtoMapper.ensureInitialized()
.hashValue(this as IsolateSyncDto);
}
}
extension IsolateSyncDtoValueCopy<$R, $Out>
on ObjectCopyWith<$R, IsolateSyncDto, $Out> {
IsolateSyncDtoCopyWith<$R, IsolateSyncDto, $Out> get $asIsolateSyncDto =>
$base.as((v, t, t2) => _IsolateSyncDtoCopyWithImpl(v, t, t2));
}
abstract class IsolateSyncDtoCopyWith<$R, $In extends IsolateSyncDto, $Out>
implements ClassCopyWith<$R, $In, $Out> {
IsolateStateCopyWith<$R, IsolateState, IsolateState> get isolateState;
IsolateCommonStateCopyWith<$R, IsolateCommonState, IsolateCommonState>
get isolateCommonState;
$R call({IsolateState? isolateState, IsolateCommonState? isolateCommonState});
IsolateSyncDtoCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _IsolateSyncDtoCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, IsolateSyncDto, $Out>
implements IsolateSyncDtoCopyWith<$R, IsolateSyncDto, $Out> {
_IsolateSyncDtoCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<IsolateSyncDto> $mapper =
IsolateSyncDtoMapper.ensureInitialized();
@override
IsolateStateCopyWith<$R, IsolateState, IsolateState> get isolateState =>
$value.isolateState.copyWith.$chain((v) => call(isolateState: v));
@override
IsolateCommonStateCopyWith<$R, IsolateCommonState, IsolateCommonState>
get isolateCommonState => $value.isolateCommonState.copyWith
.$chain((v) => call(isolateCommonState: v));
@override
$R call(
{IsolateState? isolateState,
IsolateCommonState? isolateCommonState}) =>
$apply(FieldCopyWithData({
if (isolateState != null) #isolateState: isolateState,
if (isolateCommonState != null) #isolateCommonState: isolateCommonState
}));
@override
IsolateSyncDto $make(CopyWithData data) => IsolateSyncDto(
isolateState: data.get(#isolateState, or: $value.isolateState),
isolateCommonState:
data.get(#isolateCommonState, or: $value.isolateCommonState));
@override
IsolateSyncDtoCopyWith<$R2, IsolateSyncDto, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_IsolateSyncDtoCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_parent_state.dart | import 'package:common/src/model/state/isolate_common_state.dart';
import 'package:common/src/model/state/isolate_ref_state.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'isolate_parent_state.mapper.dart';
@MappableClass()
class IsolateParentState with IsolateParentStateMappable {
final IsolateCommonState commonState;
/// Isolate Id -> Isolate State
final Map<int, IsolateRefState> isolateStates;
const IsolateParentState({
required this.commonState,
required this.isolateStates,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_child_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'isolate_child_state.dart';
class IsolateChildStateMapper extends ClassMapperBase<IsolateChildState> {
IsolateChildStateMapper._();
static IsolateChildStateMapper? _instance;
static IsolateChildStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = IsolateChildStateMapper._());
IsolateCommonStateMapper.ensureInitialized();
IsolateStateMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'IsolateChildState';
static IsolateCommonState _$commonState(IsolateChildState v) => v.commonState;
static const Field<IsolateChildState, IsolateCommonState> _f$commonState =
Field('commonState', _$commonState);
static IsolateState _$isolateState(IsolateChildState v) => v.isolateState;
static const Field<IsolateChildState, IsolateState> _f$isolateState =
Field('isolateState', _$isolateState);
@override
final Map<Symbol, Field<IsolateChildState, dynamic>> fields = const {
#commonState: _f$commonState,
#isolateState: _f$isolateState,
};
static IsolateChildState _instantiate(DecodingData data) {
return IsolateChildState(
commonState: data.dec(_f$commonState),
isolateState: data.dec(_f$isolateState));
}
@override
final Function instantiate = _instantiate;
static IsolateChildState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<IsolateChildState>(map);
}
static IsolateChildState deserialize(String json) {
return ensureInitialized().decodeJson<IsolateChildState>(json);
}
}
mixin IsolateChildStateMappable {
String serialize() {
return IsolateChildStateMapper.ensureInitialized()
.encodeJson<IsolateChildState>(this as IsolateChildState);
}
Map<String, dynamic> toJson() {
return IsolateChildStateMapper.ensureInitialized()
.encodeMap<IsolateChildState>(this as IsolateChildState);
}
IsolateChildStateCopyWith<IsolateChildState, IsolateChildState,
IsolateChildState>
get copyWith => _IsolateChildStateCopyWithImpl(
this as IsolateChildState, $identity, $identity);
@override
String toString() {
return IsolateChildStateMapper.ensureInitialized()
.stringifyValue(this as IsolateChildState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
IsolateChildStateMapper.ensureInitialized()
.isValueEqual(this as IsolateChildState, other));
}
@override
int get hashCode {
return IsolateChildStateMapper.ensureInitialized()
.hashValue(this as IsolateChildState);
}
}
extension IsolateChildStateValueCopy<$R, $Out>
on ObjectCopyWith<$R, IsolateChildState, $Out> {
IsolateChildStateCopyWith<$R, IsolateChildState, $Out>
get $asIsolateChildState =>
$base.as((v, t, t2) => _IsolateChildStateCopyWithImpl(v, t, t2));
}
abstract class IsolateChildStateCopyWith<$R, $In extends IsolateChildState,
$Out> implements ClassCopyWith<$R, $In, $Out> {
IsolateCommonStateCopyWith<$R, IsolateCommonState, IsolateCommonState>
get commonState;
IsolateStateCopyWith<$R, IsolateState, IsolateState> get isolateState;
$R call({IsolateCommonState? commonState, IsolateState? isolateState});
IsolateChildStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _IsolateChildStateCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, IsolateChildState, $Out>
implements IsolateChildStateCopyWith<$R, IsolateChildState, $Out> {
_IsolateChildStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<IsolateChildState> $mapper =
IsolateChildStateMapper.ensureInitialized();
@override
IsolateCommonStateCopyWith<$R, IsolateCommonState, IsolateCommonState>
get commonState =>
$value.commonState.copyWith.$chain((v) => call(commonState: v));
@override
IsolateStateCopyWith<$R, IsolateState, IsolateState> get isolateState =>
$value.isolateState.copyWith.$chain((v) => call(isolateState: v));
@override
$R call({IsolateCommonState? commonState, IsolateState? isolateState}) =>
$apply(FieldCopyWithData({
if (commonState != null) #commonState: commonState,
if (isolateState != null) #isolateState: isolateState
}));
@override
IsolateChildState $make(CopyWithData data) => IsolateChildState(
commonState: data.get(#commonState, or: $value.commonState),
isolateState: data.get(#isolateState, or: $value.isolateState));
@override
IsolateChildStateCopyWith<$R2, IsolateChildState, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_IsolateChildStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_child_state.dart | import 'package:common/src/model/state/isolate_common_state.dart';
import 'package:common/src/model/state/isolate_state.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'isolate_child_state.mapper.dart';
@MappableClass()
class IsolateChildState with IsolateChildStateMappable {
final IsolateCommonState commonState;
/// The current isolate state.
final IsolateState isolateState;
const IsolateChildState({
required this.commonState,
required this.isolateState,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_state.dart | import 'package:dart_mappable/dart_mappable.dart';
part 'isolate_state.mapper.dart';
enum IsolateType {
/// The multicast isolate is responsible for sending and receiving multicast messages.
/// There is only one multicast isolate per device.
multicast,
/// The isolate is responsible for discovering other devices on the network by
/// sending HTTP requests to the other devices.
/// There is only one discovery isolate per device.
httpDiscovery,
/// The isolate where the HTTP server is running.
/// There is as many isolates as there are CPU cores.
httpServer,
/// The isolate where data is sent to the server.
/// There is as many isolates as there are CPU cores.
httpClient,
}
@MappableClass()
class IsolateState with IsolateStateMappable {
final int? isolateId;
final IsolateType? isolateType;
const IsolateState({
required this.isolateId,
required this.isolateType,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_common_state.dart | import 'package:common/src/model/stored_security_context.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'isolate_common_state.mapper.dart';
/// The state that is synced across all isolates.
@MappableClass()
class IsolateCommonState with IsolateCommonStateMappable {
final StoredSecurityContext? securityContext;
const IsolateCommonState({
required this.securityContext,
});
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/state/isolate_ref_state.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'isolate_ref_state.dart';
class IsolateRefStateMapper extends ClassMapperBase<IsolateRefState> {
IsolateRefStateMapper._();
static IsolateRefStateMapper? _instance;
static IsolateRefStateMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = IsolateRefStateMapper._());
IsolateStateMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'IsolateRefState';
static IsolateCommunication<dynamic, dynamic> _$communication(
IsolateRefState v) =>
v.communication;
static const Field<IsolateRefState, IsolateCommunication<dynamic, dynamic>>
_f$communication = Field('communication', _$communication);
static IsolateState _$isolateState(IsolateRefState v) => v.isolateState;
static const Field<IsolateRefState, IsolateState> _f$isolateState =
Field('isolateState', _$isolateState);
@override
final Map<Symbol, Field<IsolateRefState, dynamic>> fields = const {
#communication: _f$communication,
#isolateState: _f$isolateState,
};
static IsolateRefState _instantiate(DecodingData data) {
return IsolateRefState(
communication: data.dec(_f$communication),
isolateState: data.dec(_f$isolateState));
}
@override
final Function instantiate = _instantiate;
static IsolateRefState fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<IsolateRefState>(map);
}
static IsolateRefState deserialize(String json) {
return ensureInitialized().decodeJson<IsolateRefState>(json);
}
}
mixin IsolateRefStateMappable {
String serialize() {
return IsolateRefStateMapper.ensureInitialized()
.encodeJson<IsolateRefState>(this as IsolateRefState);
}
Map<String, dynamic> toJson() {
return IsolateRefStateMapper.ensureInitialized()
.encodeMap<IsolateRefState>(this as IsolateRefState);
}
IsolateRefStateCopyWith<IsolateRefState, IsolateRefState, IsolateRefState>
get copyWith => _IsolateRefStateCopyWithImpl(
this as IsolateRefState, $identity, $identity);
@override
String toString() {
return IsolateRefStateMapper.ensureInitialized()
.stringifyValue(this as IsolateRefState);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
IsolateRefStateMapper.ensureInitialized()
.isValueEqual(this as IsolateRefState, other));
}
@override
int get hashCode {
return IsolateRefStateMapper.ensureInitialized()
.hashValue(this as IsolateRefState);
}
}
extension IsolateRefStateValueCopy<$R, $Out>
on ObjectCopyWith<$R, IsolateRefState, $Out> {
IsolateRefStateCopyWith<$R, IsolateRefState, $Out> get $asIsolateRefState =>
$base.as((v, t, t2) => _IsolateRefStateCopyWithImpl(v, t, t2));
}
abstract class IsolateRefStateCopyWith<$R, $In extends IsolateRefState, $Out>
implements ClassCopyWith<$R, $In, $Out> {
IsolateStateCopyWith<$R, IsolateState, IsolateState> get isolateState;
$R call(
{IsolateCommunication<dynamic, dynamic>? communication,
IsolateState? isolateState});
IsolateRefStateCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _IsolateRefStateCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, IsolateRefState, $Out>
implements IsolateRefStateCopyWith<$R, IsolateRefState, $Out> {
_IsolateRefStateCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<IsolateRefState> $mapper =
IsolateRefStateMapper.ensureInitialized();
@override
IsolateStateCopyWith<$R, IsolateState, IsolateState> get isolateState =>
$value.isolateState.copyWith.$chain((v) => call(isolateState: v));
@override
$R call(
{IsolateCommunication<dynamic, dynamic>? communication,
IsolateState? isolateState}) =>
$apply(FieldCopyWithData({
if (communication != null) #communication: communication,
if (isolateState != null) #isolateState: isolateState
}));
@override
IsolateRefState $make(CopyWithData data) => IsolateRefState(
communication: data.get(#communication, or: $value.communication),
isolateState: data.get(#isolateState, or: $value.isolateState));
@override
IsolateRefStateCopyWith<$R2, IsolateRefState, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_IsolateRefStateCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/prepare_upload_request_dto.dart | import 'package:common/src/model/dto/file_dto.dart';
import 'package:common/src/model/dto/info_register_dto.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'prepare_upload_request_dto.mapper.dart';
@MappableClass()
class PrepareUploadRequestDto with PrepareUploadRequestDtoMappable {
final InfoRegisterDto info;
final Map<String, FileDto> files;
const PrepareUploadRequestDto({
required this.info,
required this.files,
});
static const fromJson = PrepareUploadRequestDtoMapper.fromJson;
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/receive_request_response_dto.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'receive_request_response_dto.dart';
class ReceiveRequestResponseDtoMapper
extends ClassMapperBase<ReceiveRequestResponseDto> {
ReceiveRequestResponseDtoMapper._();
static ReceiveRequestResponseDtoMapper? _instance;
static ReceiveRequestResponseDtoMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals
.use(_instance = ReceiveRequestResponseDtoMapper._());
InfoDtoMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'ReceiveRequestResponseDto';
static InfoDto _$info(ReceiveRequestResponseDto v) => v.info;
static const Field<ReceiveRequestResponseDto, InfoDto> _f$info =
Field('info', _$info);
static String _$sessionId(ReceiveRequestResponseDto v) => v.sessionId;
static const Field<ReceiveRequestResponseDto, String> _f$sessionId =
Field('sessionId', _$sessionId);
static Map<String, FileDto> _$files(ReceiveRequestResponseDto v) => v.files;
static const Field<ReceiveRequestResponseDto, Map<String, FileDto>> _f$files =
Field('files', _$files);
@override
final Map<Symbol, Field<ReceiveRequestResponseDto, dynamic>> fields = const {
#info: _f$info,
#sessionId: _f$sessionId,
#files: _f$files,
};
static ReceiveRequestResponseDto _instantiate(DecodingData data) {
return ReceiveRequestResponseDto(
info: data.dec(_f$info),
sessionId: data.dec(_f$sessionId),
files: data.dec(_f$files));
}
@override
final Function instantiate = _instantiate;
static ReceiveRequestResponseDto fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<ReceiveRequestResponseDto>(map);
}
static ReceiveRequestResponseDto deserialize(String json) {
return ensureInitialized().decodeJson<ReceiveRequestResponseDto>(json);
}
}
mixin ReceiveRequestResponseDtoMappable {
String serialize() {
return ReceiveRequestResponseDtoMapper.ensureInitialized()
.encodeJson<ReceiveRequestResponseDto>(
this as ReceiveRequestResponseDto);
}
Map<String, dynamic> toJson() {
return ReceiveRequestResponseDtoMapper.ensureInitialized()
.encodeMap<ReceiveRequestResponseDto>(
this as ReceiveRequestResponseDto);
}
ReceiveRequestResponseDtoCopyWith<ReceiveRequestResponseDto,
ReceiveRequestResponseDto, ReceiveRequestResponseDto>
get copyWith => _ReceiveRequestResponseDtoCopyWithImpl(
this as ReceiveRequestResponseDto, $identity, $identity);
@override
String toString() {
return ReceiveRequestResponseDtoMapper.ensureInitialized()
.stringifyValue(this as ReceiveRequestResponseDto);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
ReceiveRequestResponseDtoMapper.ensureInitialized()
.isValueEqual(this as ReceiveRequestResponseDto, other));
}
@override
int get hashCode {
return ReceiveRequestResponseDtoMapper.ensureInitialized()
.hashValue(this as ReceiveRequestResponseDto);
}
}
extension ReceiveRequestResponseDtoValueCopy<$R, $Out>
on ObjectCopyWith<$R, ReceiveRequestResponseDto, $Out> {
ReceiveRequestResponseDtoCopyWith<$R, ReceiveRequestResponseDto, $Out>
get $asReceiveRequestResponseDto => $base
.as((v, t, t2) => _ReceiveRequestResponseDtoCopyWithImpl(v, t, t2));
}
abstract class ReceiveRequestResponseDtoCopyWith<
$R,
$In extends ReceiveRequestResponseDto,
$Out> implements ClassCopyWith<$R, $In, $Out> {
InfoDtoCopyWith<$R, InfoDto, InfoDto> get info;
MapCopyWith<$R, String, FileDto, ObjectCopyWith<$R, FileDto, FileDto>>
get files;
$R call({InfoDto? info, String? sessionId, Map<String, FileDto>? files});
ReceiveRequestResponseDtoCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _ReceiveRequestResponseDtoCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, ReceiveRequestResponseDto, $Out>
implements
ReceiveRequestResponseDtoCopyWith<$R, ReceiveRequestResponseDto, $Out> {
_ReceiveRequestResponseDtoCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<ReceiveRequestResponseDto> $mapper =
ReceiveRequestResponseDtoMapper.ensureInitialized();
@override
InfoDtoCopyWith<$R, InfoDto, InfoDto> get info =>
$value.info.copyWith.$chain((v) => call(info: v));
@override
MapCopyWith<$R, String, FileDto, ObjectCopyWith<$R, FileDto, FileDto>>
get files => MapCopyWith($value.files,
(v, t) => ObjectCopyWith(v, $identity, t), (v) => call(files: v));
@override
$R call({InfoDto? info, String? sessionId, Map<String, FileDto>? files}) =>
$apply(FieldCopyWithData({
if (info != null) #info: info,
if (sessionId != null) #sessionId: sessionId,
if (files != null) #files: files
}));
@override
ReceiveRequestResponseDto $make(CopyWithData data) =>
ReceiveRequestResponseDto(
info: data.get(#info, or: $value.info),
sessionId: data.get(#sessionId, or: $value.sessionId),
files: data.get(#files, or: $value.files));
@override
ReceiveRequestResponseDtoCopyWith<$R2, ReceiveRequestResponseDto, $Out2>
$chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_ReceiveRequestResponseDtoCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/info_dto.dart | import 'package:common/src/constants.dart';
import 'package:common/src/model/device.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'info_dto.mapper.dart';
@MappableClass()
class InfoDto with InfoDtoMappable {
final String alias;
final String? version; // v2, format: major.minor
final String? deviceModel;
final DeviceType? deviceType;
final String? fingerprint; // v2
final bool? download; // v2
const InfoDto({
required this.alias,
required this.version,
required this.deviceModel,
required this.deviceType,
required this.fingerprint,
required this.download,
});
static const fromJson = InfoDtoMapper.fromJson;
}
extension InfoToDeviceExt on InfoDto {
/// Convert [InfoDto] to [Device].
/// Since this HTTP request was successful, the [port] and [https] are known.
Device toDevice(String ip, int port, bool https) {
return Device(
ip: ip,
version: version ?? fallbackProtocolVersion,
port: port,
https: https,
fingerprint: fingerprint ?? '',
alias: alias,
deviceModel: deviceModel,
deviceType: deviceType ?? DeviceType.desktop,
download: download ?? false,
);
}
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/multicast_dto.dart | import 'package:common/common.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'multicast_dto.mapper.dart';
@MappableEnum(defaultValue: ProtocolType.https)
enum ProtocolType { http, https }
@MappableClass()
class MulticastDto with MulticastDtoMappable {
final String alias;
final String? version; // v2, format: major.minor
final String? deviceModel;
final DeviceType? deviceType; // nullable since v2
final String fingerprint;
final int? port; // v2
final ProtocolType? protocol; // v2
final bool? download; // v2
final bool? announcement; // v1
final bool? announce; // v2
const MulticastDto({
required this.alias,
required this.version,
required this.deviceModel,
required this.deviceType,
required this.fingerprint,
required this.port,
required this.protocol,
required this.download,
required this.announcement,
required this.announce,
});
static const fromJson = MulticastDtoMapper.fromJson;
}
extension MulticastDtoToDeviceExt on MulticastDto {
Device toDevice(String ip, int ownPort, bool ownHttps) {
return Device(
ip: ip,
version: version ?? fallbackProtocolVersion,
port: port ?? ownPort,
https: protocol != null ? protocol == ProtocolType.https : ownHttps,
fingerprint: fingerprint,
alias: alias,
deviceModel: deviceModel,
deviceType: deviceType ?? DeviceType.desktop,
download: download ?? false,
);
}
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/register_dto.dart | import 'package:common/src/constants.dart';
import 'package:common/src/model/device.dart';
import 'package:common/src/model/dto/multicast_dto.dart';
import 'package:dart_mappable/dart_mappable.dart';
part 'register_dto.mapper.dart';
@MappableClass()
class RegisterDto with RegisterDtoMappable {
final String alias;
final String? version; // v2, format: major.minor
final String? deviceModel;
final DeviceType? deviceType;
final String fingerprint;
final int? port; // v2
final ProtocolType? protocol; // v2
final bool? download; // v2
const RegisterDto({
required this.alias,
required this.version,
required this.deviceModel,
required this.deviceType,
required this.fingerprint,
required this.port,
required this.protocol,
required this.download,
});
static const fromJson = RegisterDtoMapper.fromJson;
}
extension RegisterDtoExt on RegisterDto {
Device toDevice(String ip, int ownPort, bool ownHttps) {
return Device(
ip: ip,
version: version ?? fallbackProtocolVersion,
port: port ?? ownPort,
https: protocol != null ? protocol == ProtocolType.https : ownHttps,
fingerprint: fingerprint,
alias: alias,
deviceModel: deviceModel,
deviceType: deviceType ?? DeviceType.desktop,
download: download ?? false,
);
}
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/prepare_upload_response_dto.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'prepare_upload_response_dto.dart';
class PrepareUploadResponseDtoMapper
extends ClassMapperBase<PrepareUploadResponseDto> {
PrepareUploadResponseDtoMapper._();
static PrepareUploadResponseDtoMapper? _instance;
static PrepareUploadResponseDtoMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals
.use(_instance = PrepareUploadResponseDtoMapper._());
}
return _instance!;
}
@override
final String id = 'PrepareUploadResponseDto';
static String _$sessionId(PrepareUploadResponseDto v) => v.sessionId;
static const Field<PrepareUploadResponseDto, String> _f$sessionId =
Field('sessionId', _$sessionId);
static Map<String, String> _$files(PrepareUploadResponseDto v) => v.files;
static const Field<PrepareUploadResponseDto, Map<String, String>> _f$files =
Field('files', _$files);
@override
final Map<Symbol, Field<PrepareUploadResponseDto, dynamic>> fields = const {
#sessionId: _f$sessionId,
#files: _f$files,
};
static PrepareUploadResponseDto _instantiate(DecodingData data) {
return PrepareUploadResponseDto(
sessionId: data.dec(_f$sessionId), files: data.dec(_f$files));
}
@override
final Function instantiate = _instantiate;
static PrepareUploadResponseDto fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<PrepareUploadResponseDto>(map);
}
static PrepareUploadResponseDto deserialize(String json) {
return ensureInitialized().decodeJson<PrepareUploadResponseDto>(json);
}
}
mixin PrepareUploadResponseDtoMappable {
String serialize() {
return PrepareUploadResponseDtoMapper.ensureInitialized()
.encodeJson<PrepareUploadResponseDto>(this as PrepareUploadResponseDto);
}
Map<String, dynamic> toJson() {
return PrepareUploadResponseDtoMapper.ensureInitialized()
.encodeMap<PrepareUploadResponseDto>(this as PrepareUploadResponseDto);
}
PrepareUploadResponseDtoCopyWith<PrepareUploadResponseDto,
PrepareUploadResponseDto, PrepareUploadResponseDto>
get copyWith => _PrepareUploadResponseDtoCopyWithImpl(
this as PrepareUploadResponseDto, $identity, $identity);
@override
String toString() {
return PrepareUploadResponseDtoMapper.ensureInitialized()
.stringifyValue(this as PrepareUploadResponseDto);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
PrepareUploadResponseDtoMapper.ensureInitialized()
.isValueEqual(this as PrepareUploadResponseDto, other));
}
@override
int get hashCode {
return PrepareUploadResponseDtoMapper.ensureInitialized()
.hashValue(this as PrepareUploadResponseDto);
}
}
extension PrepareUploadResponseDtoValueCopy<$R, $Out>
on ObjectCopyWith<$R, PrepareUploadResponseDto, $Out> {
PrepareUploadResponseDtoCopyWith<$R, PrepareUploadResponseDto, $Out>
get $asPrepareUploadResponseDto => $base
.as((v, t, t2) => _PrepareUploadResponseDtoCopyWithImpl(v, t, t2));
}
abstract class PrepareUploadResponseDtoCopyWith<
$R,
$In extends PrepareUploadResponseDto,
$Out> implements ClassCopyWith<$R, $In, $Out> {
MapCopyWith<$R, String, String, ObjectCopyWith<$R, String, String>> get files;
$R call({String? sessionId, Map<String, String>? files});
PrepareUploadResponseDtoCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _PrepareUploadResponseDtoCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, PrepareUploadResponseDto, $Out>
implements
PrepareUploadResponseDtoCopyWith<$R, PrepareUploadResponseDto, $Out> {
_PrepareUploadResponseDtoCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<PrepareUploadResponseDto> $mapper =
PrepareUploadResponseDtoMapper.ensureInitialized();
@override
MapCopyWith<$R, String, String, ObjectCopyWith<$R, String, String>>
get files => MapCopyWith($value.files,
(v, t) => ObjectCopyWith(v, $identity, t), (v) => call(files: v));
@override
$R call({String? sessionId, Map<String, String>? files}) =>
$apply(FieldCopyWithData({
if (sessionId != null) #sessionId: sessionId,
if (files != null) #files: files
}));
@override
PrepareUploadResponseDto $make(CopyWithData data) => PrepareUploadResponseDto(
sessionId: data.get(#sessionId, or: $value.sessionId),
files: data.get(#files, or: $value.files));
@override
PrepareUploadResponseDtoCopyWith<$R2, PrepareUploadResponseDto, $Out2>
$chain<$R2, $Out2>(Then<$Out2, $R2> t) =>
_PrepareUploadResponseDtoCopyWithImpl($value, $cast, t);
}
| 0 |
mirrored_repositories/localsend/common/lib/src/model | mirrored_repositories/localsend/common/lib/src/model/dto/info_register_dto.mapper.dart | // coverage:ignore-file
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint
// ignore_for_file: unused_element, unnecessary_cast
// ignore_for_file: strict_raw_type, inference_failure_on_untyped_parameter
part of 'info_register_dto.dart';
class InfoRegisterDtoMapper extends ClassMapperBase<InfoRegisterDto> {
InfoRegisterDtoMapper._();
static InfoRegisterDtoMapper? _instance;
static InfoRegisterDtoMapper ensureInitialized() {
if (_instance == null) {
MapperContainer.globals.use(_instance = InfoRegisterDtoMapper._());
DeviceTypeMapper.ensureInitialized();
ProtocolTypeMapper.ensureInitialized();
}
return _instance!;
}
@override
final String id = 'InfoRegisterDto';
static String _$alias(InfoRegisterDto v) => v.alias;
static const Field<InfoRegisterDto, String> _f$alias =
Field('alias', _$alias);
static String? _$version(InfoRegisterDto v) => v.version;
static const Field<InfoRegisterDto, String> _f$version =
Field('version', _$version);
static String? _$deviceModel(InfoRegisterDto v) => v.deviceModel;
static const Field<InfoRegisterDto, String> _f$deviceModel =
Field('deviceModel', _$deviceModel);
static DeviceType? _$deviceType(InfoRegisterDto v) => v.deviceType;
static const Field<InfoRegisterDto, DeviceType> _f$deviceType =
Field('deviceType', _$deviceType);
static String? _$fingerprint(InfoRegisterDto v) => v.fingerprint;
static const Field<InfoRegisterDto, String> _f$fingerprint =
Field('fingerprint', _$fingerprint);
static int? _$port(InfoRegisterDto v) => v.port;
static const Field<InfoRegisterDto, int> _f$port = Field('port', _$port);
static ProtocolType? _$protocol(InfoRegisterDto v) => v.protocol;
static const Field<InfoRegisterDto, ProtocolType> _f$protocol =
Field('protocol', _$protocol);
static bool? _$download(InfoRegisterDto v) => v.download;
static const Field<InfoRegisterDto, bool> _f$download =
Field('download', _$download);
@override
final Map<Symbol, Field<InfoRegisterDto, dynamic>> fields = const {
#alias: _f$alias,
#version: _f$version,
#deviceModel: _f$deviceModel,
#deviceType: _f$deviceType,
#fingerprint: _f$fingerprint,
#port: _f$port,
#protocol: _f$protocol,
#download: _f$download,
};
static InfoRegisterDto _instantiate(DecodingData data) {
return InfoRegisterDto(
alias: data.dec(_f$alias),
version: data.dec(_f$version),
deviceModel: data.dec(_f$deviceModel),
deviceType: data.dec(_f$deviceType),
fingerprint: data.dec(_f$fingerprint),
port: data.dec(_f$port),
protocol: data.dec(_f$protocol),
download: data.dec(_f$download));
}
@override
final Function instantiate = _instantiate;
static InfoRegisterDto fromJson(Map<String, dynamic> map) {
return ensureInitialized().decodeMap<InfoRegisterDto>(map);
}
static InfoRegisterDto deserialize(String json) {
return ensureInitialized().decodeJson<InfoRegisterDto>(json);
}
}
mixin InfoRegisterDtoMappable {
String serialize() {
return InfoRegisterDtoMapper.ensureInitialized()
.encodeJson<InfoRegisterDto>(this as InfoRegisterDto);
}
Map<String, dynamic> toJson() {
return InfoRegisterDtoMapper.ensureInitialized()
.encodeMap<InfoRegisterDto>(this as InfoRegisterDto);
}
InfoRegisterDtoCopyWith<InfoRegisterDto, InfoRegisterDto, InfoRegisterDto>
get copyWith => _InfoRegisterDtoCopyWithImpl(
this as InfoRegisterDto, $identity, $identity);
@override
String toString() {
return InfoRegisterDtoMapper.ensureInitialized()
.stringifyValue(this as InfoRegisterDto);
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(runtimeType == other.runtimeType &&
InfoRegisterDtoMapper.ensureInitialized()
.isValueEqual(this as InfoRegisterDto, other));
}
@override
int get hashCode {
return InfoRegisterDtoMapper.ensureInitialized()
.hashValue(this as InfoRegisterDto);
}
}
extension InfoRegisterDtoValueCopy<$R, $Out>
on ObjectCopyWith<$R, InfoRegisterDto, $Out> {
InfoRegisterDtoCopyWith<$R, InfoRegisterDto, $Out> get $asInfoRegisterDto =>
$base.as((v, t, t2) => _InfoRegisterDtoCopyWithImpl(v, t, t2));
}
abstract class InfoRegisterDtoCopyWith<$R, $In extends InfoRegisterDto, $Out>
implements ClassCopyWith<$R, $In, $Out> {
$R call(
{String? alias,
String? version,
String? deviceModel,
DeviceType? deviceType,
String? fingerprint,
int? port,
ProtocolType? protocol,
bool? download});
InfoRegisterDtoCopyWith<$R2, $In, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t);
}
class _InfoRegisterDtoCopyWithImpl<$R, $Out>
extends ClassCopyWithBase<$R, InfoRegisterDto, $Out>
implements InfoRegisterDtoCopyWith<$R, InfoRegisterDto, $Out> {
_InfoRegisterDtoCopyWithImpl(super.value, super.then, super.then2);
@override
late final ClassMapperBase<InfoRegisterDto> $mapper =
InfoRegisterDtoMapper.ensureInitialized();
@override
$R call(
{String? alias,
Object? version = $none,
Object? deviceModel = $none,
Object? deviceType = $none,
Object? fingerprint = $none,
Object? port = $none,
Object? protocol = $none,
Object? download = $none}) =>
$apply(FieldCopyWithData({
if (alias != null) #alias: alias,
if (version != $none) #version: version,
if (deviceModel != $none) #deviceModel: deviceModel,
if (deviceType != $none) #deviceType: deviceType,
if (fingerprint != $none) #fingerprint: fingerprint,
if (port != $none) #port: port,
if (protocol != $none) #protocol: protocol,
if (download != $none) #download: download
}));
@override
InfoRegisterDto $make(CopyWithData data) => InfoRegisterDto(
alias: data.get(#alias, or: $value.alias),
version: data.get(#version, or: $value.version),
deviceModel: data.get(#deviceModel, or: $value.deviceModel),
deviceType: data.get(#deviceType, or: $value.deviceType),
fingerprint: data.get(#fingerprint, or: $value.fingerprint),
port: data.get(#port, or: $value.port),
protocol: data.get(#protocol, or: $value.protocol),
download: data.get(#download, or: $value.download));
@override
InfoRegisterDtoCopyWith<$R2, InfoRegisterDto, $Out2> $chain<$R2, $Out2>(
Then<$Out2, $R2> t) =>
_InfoRegisterDtoCopyWithImpl($value, $cast, t);
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.