Create management portal in Flutter (#40)
All checks were successful
BlockStorage/repertory/pipeline/head This commit looks good

Reviewed-on: #40
This commit is contained in:
2025-03-03 19:56:56 -06:00
parent c59c846856
commit d9cd2aa88a
42 changed files with 2252 additions and 84 deletions

View File

@@ -0,0 +1 @@
const String appTitle = "Repertory Management Portal";

View File

@@ -0,0 +1,6 @@
class DuplicateMountException implements Exception {
final String _name;
const DuplicateMountException({required name}) : _name = name, super();
String get name => _name;
}

View File

@@ -0,0 +1,18 @@
String formatMountName(String type, String name) {
if (type == "remote") {
return name.replaceAll("_", ":");
}
return name;
}
String initialCaps(String txt) {
if (txt.isEmpty) {
return txt;
}
if (txt.length == 1) {
return txt[0].toUpperCase();
}
return txt[0].toUpperCase() + txt.substring(1).toLowerCase();
}

View File

@@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:repertory/constants.dart' as constants;
import 'package:repertory/helpers.dart';
import 'package:repertory/models/mount.dart';
import 'package:repertory/models/mount_list.dart';
import 'package:repertory/widgets/mount_list_widget.dart';
import 'package:repertory/widgets/mount_settings.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: constants.appTitle,
theme: ThemeData(
brightness: Brightness.light,
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepOrange,
brightness: Brightness.light,
),
),
themeMode: ThemeMode.dark,
darkTheme: ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
colorScheme: ColorScheme.fromSeed(
brightness: Brightness.dark,
onSurface: Colors.white70,
seedColor: Colors.deepOrange,
surface: Color.fromARGB(255, 32, 33, 36),
surfaceContainerLow: Color.fromARGB(255, 41, 42, 45),
),
),
initialRoute: '/',
routes: {'/': (context) => const MyHomePage(title: constants.appTitle)},
onGenerateRoute: (settings) {
if (settings.name != '/settings') {
return null;
}
final mount = settings.arguments as Mount;
return MaterialPageRoute(
builder: (context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(
'${initialCaps(mount.type)} [${formatMountName(mount.type, mount.name)}] Settings',
),
),
body: MountSettingsWidget(mount: mount),
);
},
);
},
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({super.key, required this.title});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
leading: const Icon(Icons.storage),
title: Text(widget.title),
),
body: ChangeNotifierProvider(
create: (context) => MountList(),
child: MountListWidget(),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
tooltip: 'Add',
child: const Icon(Icons.add),
),
);
}
}

View File

@@ -0,0 +1,83 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:repertory/types/mount_config.dart';
class Mount with ChangeNotifier {
final MountConfig mountConfig;
Mount(this.mountConfig) {
refresh();
}
String get name => mountConfig.name;
String get path => mountConfig.path;
IconData get state => mountConfig.state;
String get type => mountConfig.type;
Future<void> _fetch() async {
final response = await http.get(
Uri.parse(
Uri.encodeFull('${Uri.base.origin}/api/v1/mount?name=$name&type=$type'),
),
);
if (response.statusCode != 200) {
return;
}
mountConfig.updateSettings(jsonDecode(response.body));
notifyListeners();
}
Future<void> _fetchStatus() async {
final response = await http.get(
Uri.parse(
Uri.encodeFull(
'${Uri.base.origin}/api/v1/mount_status?name=$name&type=$type',
),
),
);
if (response.statusCode != 200) {
return;
}
mountConfig.updateStatus(jsonDecode(response.body));
notifyListeners();
}
Future<void> mount(bool unmount, {String? location}) async {
await http.post(
Uri.parse(
Uri.encodeFull(
'${Uri.base.origin}/api/v1/mount?unmount=$unmount&name=$name&type=$type&location=$location',
),
),
);
return refresh();
}
Future<void> refresh() async {
await _fetch();
return _fetchStatus();
}
Future<void> setValue(String key, String value) async {
await http.put(
Uri.parse(
Uri.encodeFull(
'${Uri.base.origin}/api/v1/set_value_by_name?name=$name&type=$type&key=$key&value=$value',
),
),
);
return refresh();
}
Future<String?> getMountLocation() async {
return "~/mnt/encrypt";
}
}

View File

@@ -0,0 +1,67 @@
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:repertory/errors/duplicate_mount_exception.dart';
import 'package:repertory/types/mount_config.dart';
class MountList with ChangeNotifier {
MountList() {
_fetch();
}
List<MountConfig> _mountList = [];
UnmodifiableListView get items => UnmodifiableListView(_mountList);
Future<void> _fetch() async {
final response = await http.get(
Uri.parse('${Uri.base.origin}/api/v1/mount_list'),
);
if (response.statusCode == 200) {
List<MountConfig> nextList = [];
jsonDecode(response.body).forEach((key, value) {
nextList.addAll(
value.map((name) => MountConfig.fromJson(key, name)).toList(),
);
});
_sort(nextList);
_mountList = nextList;
notifyListeners();
return;
}
}
void _sort(list) {
list.sort((a, b) {
final res = a.type.compareTo(b.type);
if (res != 0) {
return res;
}
return a.name.compareTo(b.name);
});
}
void add(MountConfig config) {
var item = _mountList.firstWhereOrNull((cfg) => cfg.name == config.name);
if (item != null) {
throw DuplicateMountException(name: config.name);
}
_mountList.add(config);
_sort(_mountList);
notifyListeners();
}
void remove(String name) {
_mountList.removeWhere((item) => item.name == name);
notifyListeners();
}
}

View File

@@ -0,0 +1,31 @@
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
class MountConfig {
final String _name;
String _path = "";
Map<String, dynamic> _settings = {};
IconData _state = Icons.toggle_off;
final String _type;
MountConfig({required name, required type}) : _name = name, _type = type;
String get name => _name;
String get path => _path;
UnmodifiableMapView<String, dynamic> get settings =>
UnmodifiableMapView<String, dynamic>(_settings);
IconData get state => _state;
String get type => _type;
factory MountConfig.fromJson(String type, String name) {
return MountConfig(name: name, type: type);
}
void updateSettings(Map<String, dynamic> settings) {
_settings = settings;
}
void updateStatus(Map<String, dynamic> status) {
_path = status["Location"] as String;
_state = status["Active"] as bool ? Icons.toggle_on : Icons.toggle_off;
}
}

View File

@@ -0,0 +1,31 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:repertory/models/mount.dart';
import 'package:repertory/models/mount_list.dart';
import 'package:repertory/widgets/mount_widget.dart';
class MountListWidget extends StatefulWidget {
const MountListWidget({super.key});
@override
State<MountListWidget> createState() => _MountListWidgetState();
}
class _MountListWidgetState extends State<MountListWidget> {
@override
Widget build(BuildContext context) {
return Consumer<MountList>(
builder: (context, mountList, widget) {
return ListView.builder(
itemBuilder: (context, idx) {
return ChangeNotifierProvider(
create: (context) => Mount(mountList.items[idx]),
child: const MountWidget(),
);
},
itemCount: mountList.items.length,
);
},
);
}
}

View File

@@ -0,0 +1,568 @@
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:repertory/models/mount.dart';
import 'package:settings_ui/settings_ui.dart';
class MountSettingsWidget extends StatefulWidget {
final Mount mount;
const MountSettingsWidget({super.key, required this.mount});
@override
State<MountSettingsWidget> createState() => _MountSettingsWidgetState();
}
class _MountSettingsWidgetState extends State<MountSettingsWidget> {
Map<String, dynamic> _settings = {};
void _addBooleanSetting(list, root, key, value) {
list.add(
SettingsTile.switchTile(
leading: Icon(Icons.quiz),
title: Text(key),
initialValue: (value as bool),
onPressed: (_) {
setState(() {
root[key] = !value;
});
},
onToggle: (bool nextValue) {
setState(() {
root[key] = nextValue;
});
},
),
);
}
void _addIntSetting(list, root, key, value) {
list.add(
SettingsTile.navigation(
leading: Icon(Icons.onetwothree),
title: Text(key),
value: Text(value.toString()),
onPressed: (_) {
String updatedValue = value.toString();
showDialog(
context: context,
builder: (context) {
return AlertDialog(
actions: [
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('OK'),
onPressed: () {
setState(() {
root[key] = int.parse(updatedValue);
});
Navigator.of(context).pop();
},
),
],
content: TextField(
autofocus: true,
controller: TextEditingController(text: updatedValue),
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
keyboardType: TextInputType.number,
onChanged: (nextValue) {
updatedValue = nextValue;
},
),
title: Text(key),
);
},
);
},
),
);
}
void _addIntListSetting(
list,
root,
key,
value,
List<String> valueList,
defaultValue,
icon,
) {
list.add(
SettingsTile.navigation(
title: Text(key),
leading: Icon(icon),
value: DropdownButton<String>(
value: value.toString(),
onChanged: (newValue) {
setState(() {
root[key] = int.parse(newValue ?? defaultValue.toString());
});
},
items:
valueList.map<DropdownMenuItem<String>>((item) {
return DropdownMenuItem<String>(value: item, child: Text(item));
}).toList(),
),
),
);
}
void _addListSetting(list, root, key, value, List<String> valueList, icon) {
list.add(
SettingsTile.navigation(
title: Text(key),
leading: Icon(icon),
value: DropdownButton<String>(
value: value,
onChanged: (newValue) {
setState(() {
root[key] = newValue;
});
},
items:
valueList.map<DropdownMenuItem<String>>((item) {
return DropdownMenuItem<String>(value: item, child: Text(item));
}).toList(),
),
),
);
}
void _addPasswordSetting(list, root, key, value) {
list.add(
SettingsTile.navigation(
leading: Icon(Icons.password),
title: Text(key),
value: Text('*' * (value as String).length),
),
);
}
void _addStringSetting(list, root, key, value, icon) {
list.add(
SettingsTile.navigation(
leading: Icon(icon),
title: Text(key),
value: Text(value),
onPressed: (_) {
String updatedValue = value;
showDialog(
context: context,
builder: (context) {
return AlertDialog(
actions: [
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: Text('OK'),
onPressed: () {
setState(() {
root[key] = updatedValue;
});
Navigator.of(context).pop();
},
),
],
content: TextField(
autofocus: true,
controller: TextEditingController(text: updatedValue),
onChanged: (value) {
updatedValue = value;
},
),
title: Text(key),
);
},
);
},
),
);
}
@override
Widget build(BuildContext context) {
List<SettingsTile> commonSettings = [];
List<SettingsTile> encryptConfigSettings = [];
List<SettingsTile> hostConfigSettings = [];
List<SettingsTile> remoteConfigSettings = [];
List<SettingsTile> remoteMountSettings = [];
List<SettingsTile> s3ConfigSettings = [];
List<SettingsTile> siaConfigSettings = [];
_settings.forEach((key, value) {
if (key == "ApiAuth") {
_addPasswordSetting(commonSettings, _settings, key, value);
} else if (key == "ApiPort") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "ApiUser") {
_addStringSetting(commonSettings, _settings, key, value, Icons.person);
} else if (key == "DatabaseType") {
_addListSetting(commonSettings, _settings, key, value, [
"rocksdb",
"sqlite",
], Icons.dataset);
} else if (key == "DownloadTimeoutSeconds") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "EnableDownloadTimeout") {
_addBooleanSetting(commonSettings, _settings, key, value);
} else if (key == "EnableDriveEvents") {
_addBooleanSetting(commonSettings, _settings, key, value);
} else if (key == "EventLevel") {
_addListSetting(commonSettings, _settings, key, value, [
"critical",
"error",
"warn",
"info",
"debug",
"trace",
], Icons.event);
} else if (key == "EvictionDelayMinutes") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "EvictionUseAccessedTime") {
_addBooleanSetting(commonSettings, _settings, key, value);
} else if (key == "MaxCacheSizeBytes") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "MaxUploadCount") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "OnlineCheckRetrySeconds") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "PreferredDownloadType") {
_addListSetting(commonSettings, _settings, key, value, [
"default",
"direct",
"ring_buffer",
], Icons.download);
} else if (key == "RetryReadCount") {
_addIntSetting(commonSettings, _settings, key, value);
} else if (key == "RingBufferFileSize") {
_addIntListSetting(
commonSettings,
_settings,
key,
value,
["128", "256", "512", "1024", "2048"],
512,
Icons.animation,
);
} else if (key == "EncryptConfig") {
value.forEach((subKey, subValue) {
if (subKey == "EncryptionToken") {
_addPasswordSetting(
encryptConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "Path") {
_addStringSetting(
encryptConfigSettings,
_settings[key],
subKey,
subValue,
Icons.folder,
);
}
});
} else if (key == "HostConfig") {
value.forEach((subKey, subValue) {
if (subKey == "AgentString") {
_addStringSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
Icons.support_agent,
);
} else if (subKey == "ApiPassword") {
_addPasswordSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "ApiPort") {
_addIntSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "ApiUser") {
_addStringSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
Icons.person,
);
} else if (subKey == "HostNameOrIp") {
_addStringSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
Icons.computer,
);
} else if (subKey == "Path") {
_addStringSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
Icons.route,
);
} else if (subKey == "Protocol") {
_addListSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
["http", "https"],
Icons.http,
);
} else if (subKey == "TimeoutMs") {
_addIntSetting(
hostConfigSettings,
_settings[key],
subKey,
subValue,
);
}
});
} else if (key == "RemoteConfig") {
value.forEach((subKey, subValue) {
if (subKey == "ApiPort") {
_addIntSetting(
remoteConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "EncryptionToken") {
_addPasswordSetting(
remoteConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "HostNameOrIp") {
_addStringSetting(
remoteConfigSettings,
_settings[key],
subKey,
subValue,
Icons.computer,
);
} else if (subKey == "MaxConnections") {
_addIntSetting(
remoteConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "ReceiveTimeoutMs") {
_addIntSetting(
remoteConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "SendTimeoutMs") {
_addIntSetting(
remoteConfigSettings,
_settings[key],
subKey,
subValue,
);
}
});
} else if (key == "RemoteMount") {
value.forEach((subKey, subValue) {
if (subKey == "Enable") {
List<SettingsTile> tempSettings = [];
_addBooleanSetting(tempSettings, _settings[key], subKey, subValue);
remoteMountSettings.insertAll(0, tempSettings);
} else if (subKey == "ApiPort") {
_addIntSetting(
remoteMountSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "ClientPoolSize") {
_addIntSetting(
remoteMountSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "EncryptionToken") {
_addPasswordSetting(
remoteMountSettings,
_settings[key],
subKey,
subValue,
);
}
});
} else if (key == "S3Config") {
value.forEach((subKey, subValue) {
if (subKey == "AccessKey") {
_addPasswordSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "Bucket") {
_addStringSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
Icons.folder,
);
} else if (subKey == "EncryptionToken") {
_addPasswordSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "Region") {
_addStringSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
Icons.map,
);
} else if (subKey == "SecretKey") {
_addPasswordSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "TimeoutMs") {
_addIntSetting(s3ConfigSettings, _settings[key], subKey, subValue);
} else if (subKey == "URL") {
_addStringSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
Icons.http,
);
} else if (subKey == "UsePathStyle") {
_addBooleanSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
);
} else if (subKey == "UseRegionInURL") {
_addBooleanSetting(
s3ConfigSettings,
_settings[key],
subKey,
subValue,
);
}
});
} else if (key == "SiaConfig") {
value.forEach((subKey, subValue) {
if (subKey == "Bucket") {
_addStringSetting(
siaConfigSettings,
_settings[key],
subKey,
subValue,
Icons.folder,
);
}
});
}
});
return SettingsList(
shrinkWrap: false,
sections: [
if (encryptConfigSettings.isNotEmpty)
SettingsSection(
title: const Text('Encrypt Config'),
tiles: encryptConfigSettings,
),
if (hostConfigSettings.isNotEmpty)
SettingsSection(
title: const Text('Host Config'),
tiles: hostConfigSettings,
),
if (remoteConfigSettings.isNotEmpty)
SettingsSection(
title: const Text('Remote Config'),
tiles: remoteConfigSettings,
),
if (s3ConfigSettings.isNotEmpty)
SettingsSection(
title: const Text('S3 Config'),
tiles: s3ConfigSettings,
),
if (siaConfigSettings.isNotEmpty)
SettingsSection(
title: const Text('Sia Config'),
tiles: siaConfigSettings,
),
if (remoteMountSettings.isNotEmpty)
SettingsSection(
title: const Text('Remote Mount'),
tiles:
_settings["RemoteMount"]["Enable"] as bool
? remoteMountSettings
: [remoteMountSettings[0]],
),
SettingsSection(title: const Text('Settings'), tiles: commonSettings),
],
);
}
@override
void dispose() {
var settings = widget.mount.mountConfig.settings;
if (!DeepCollectionEquality().equals(_settings, settings)) {
_settings.forEach((key, value) {
if (!DeepCollectionEquality().equals(settings[key], value)) {
if (value is Map<String, dynamic>) {
value.forEach((subKey, subValue) {
if (!DeepCollectionEquality().equals(
settings[key][subKey],
subValue,
)) {
widget.mount.setValue('$key.$subKey', subValue.toString());
}
});
} else {
widget.mount.setValue(key, value.toString());
}
}
});
}
super.dispose();
}
@override
void initState() {
_settings = jsonDecode(jsonEncode(widget.mount.mountConfig.settings));
super.initState();
}
}

View File

@@ -0,0 +1,112 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:repertory/helpers.dart';
import 'package:repertory/models/mount.dart';
class MountWidget extends StatefulWidget {
const MountWidget({super.key});
@override
State<MountWidget> createState() => _MountWidgetState();
}
class _MountWidgetState extends State<MountWidget> {
Timer? _timer;
bool _enabled = true;
@override
Widget build(BuildContext context) {
return Card(
child: Consumer<Mount>(
builder: (context, mount, widget) {
final textColor = Theme.of(context).colorScheme.onSurface;
final subTextColor =
Theme.of(context).brightness == Brightness.dark
? Colors.white38
: Colors.black87;
final isActive = mount.state == Icons.toggle_on;
final nameText = SelectableText(
formatMountName(mount.type, mount.name),
style: TextStyle(color: subTextColor),
);
return ListTile(
isThreeLine: true,
leading: IconButton(
icon: Icon(Icons.settings, color: textColor),
onPressed: () {
Navigator.pushNamed(context, '/settings', arguments: mount);
},
),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
nameText,
SelectableText(
mount.path,
style: TextStyle(color: subTextColor),
),
],
),
title: SelectableText(
initialCaps(mount.type),
style: TextStyle(color: textColor, fontWeight: FontWeight.bold),
),
trailing: IconButton(
icon: Icon(
mount.state,
color:
isActive ? Color.fromARGB(255, 163, 96, 76) : subTextColor,
),
onPressed:
_enabled
? () async {
setState(() {
_enabled = false;
});
String? location = mount.path;
if (!isActive && mount.path.isEmpty) {
location = await mount.getMountLocation();
if (location == null) {}
}
mount
.mount(isActive, location: location)
.then((_) {
setState(() {
_enabled = true;
});
})
.catchError((_) {
setState(() {
_enabled = true;
});
});
}
: null,
),
);
},
),
);
}
@override
void dispose() {
_timer?.cancel();
_timer = null;
super.dispose();
}
@override
void initState() {
super.initState();
_timer = Timer.periodic(const Duration(seconds: 5), (_) {
Provider.of<Mount>(context, listen: false).refresh();
});
}
}