Added about room screen.

NOTE: Some of the route redirect options are still missing.
There should also be a delete Room option
This commit is contained in:
Jakob Meier 2023-03-22 21:17:03 +01:00
parent f3ac4a502c
commit c54e4f519f
No known key found for this signature in database
GPG key ID: 66BDC7E6A01A6152
4 changed files with 445 additions and 91 deletions

View file

@ -1,29 +1,30 @@
/* /*
* Tool to automatically generate english text from error * Tool to automatically generate english text from error
*/ */
String errorAsString(Map<String, dynamic> json) { String errorAsString(Map<String, dynamic> json) {
switch (json['data']) { switch (json['data']) {
case 'notfound': case 'notfound':
return 'Endpoint not found'; return 'Endpoint not found';
case 'wrongstate': case 'wrongstate':
return 'Missing data'; return 'Missing data';
case 'data': case 'data':
return 'Invalid data'; return 'Invalid data';
case 'right': case 'roomAdmin':
return 'You are not allowed to perform this action'; case 'right':
case 'server': return 'You are not allowed to perform this action';
return 'Server error'; case 'server':
case 'closed': return 'Server error';
return 'Server cannot be reached'; case 'closed':
case 'auth': return 'Server cannot be reached';
return 'Username or password wrong'; case 'auth':
case 'ota': return 'Username or password wrong';
return 'Invalid OTA'; case 'ota':
case 'existence': return 'Invalid OTA';
return 'Username unavailable'; case 'existence':
case 'config': return 'Username unavailable';
return 'Server reached user limit'; case 'config':
} return 'Server reached user limit';
}
return "Unknown Error"; return "Unknown Error";
} }

View file

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:outbag_app/backend/user.dart'; import 'package:outbag_app/backend/user.dart';
import 'package:outbag_app/screens/room/join.dart'; import 'package:outbag_app/screens/room/join.dart';
import 'package:outbag_app/screens/room/new.dart'; import 'package:outbag_app/screens/room/new.dart';
import 'package:outbag_app/screens/room/shopping_list.dart';
import './screens/home.dart'; import './screens/home.dart';
import './screens/welcome.dart'; import './screens/welcome.dart';
import './screens/room.dart'; import './screens/room.dart';
@ -11,29 +12,26 @@ import 'package:routemaster/routemaster.dart';
// routes when user is not logged in // routes when user is not logged in
final routesUnauthorized = RouteMap(routes: { final routesUnauthorized = RouteMap(routes: {
'/welcome/': (_) => const MaterialPage(child: WelcomePage()), '/welcome/': (_) => const MaterialPage(child: WelcomePage()),
'/signup': (_) => const MaterialPage(child: AuthPage(mode: Mode.signup)), '/signup': (_) => const MaterialPage(child: AuthPage(mode: Mode.signup)),
'/signupOTA': (_) => '/signupOTA': (_) =>
const MaterialPage(child: AuthPage(mode: Mode.signupOTA)), const MaterialPage(child: AuthPage(mode: Mode.signupOTA)),
'/signin': (_) => const MaterialPage(child: AuthPage(mode: Mode.signin)), '/signin': (_) => const MaterialPage(child: AuthPage(mode: Mode.signin)),
}, onUnknownRoute: (_) => const MaterialPage(child: WelcomePage())); }, onUnknownRoute: (_) => const MaterialPage(child: WelcomePage()));
// routes when user is logged in // routes when user is logged in
final routesLoggedIn = RouteMap(routes: { final routesLoggedIn = RouteMap(routes: {
'/': (_) => const MaterialPage(child: HomePage()), '/': (_) => const MaterialPage(child: HomePage()),
'/add-room/new': (_) => const MaterialPage(child: NewRoomPage()), '/add-room/new': (_) => const MaterialPage(child: NewRoomPage()),
'/add-room': (_) => const MaterialPage(child: JoinRoomPage()), '/add-room': (_) => const MaterialPage(child: JoinRoomPage()),
'/r/:server/:tag/:page?': (info) => MaterialPage( '/r/:server/:tag/': (info) {
child: RoomPage(info.pathParameters['server'] ?? "", final server = info.pathParameters['server'] ?? "";
info.pathParameters['tag'] ?? "", final tag = info.pathParameters['tag'] ?? "";
page: info.pathParameters['page'] ?? ""),
), return MaterialPage(
'/r/:server/:tag/': (info) => MaterialPage( child: RoomPage(server, tag));
child: RoomPage(info.pathParameters['server'] ?? "", },
info.pathParameters['tag'] ?? "", }, onUnknownRoute: (_) => const Redirect('/'));
page: 'list'),
),
}, onUnknownRoute: (_) => const Redirect('/'));
void main() { void main() {
WidgetsFlutterBinding.ensureInitialized(); WidgetsFlutterBinding.ensureInitialized();
@ -61,56 +59,56 @@ class _OutbagAppState extends State {
// with existing details // with existing details
(() async { (() async {
User credentials; User credentials;
try { try {
credentials = await User.fromDisk(); credentials = await User.fromDisk();
} catch (_) { } catch (_) {
// invalid credentials // invalid credentials
// log out // log out
setState(() { setState(() {
isAuthorized = false; isAuthorized = false;
}); });
return; return;
} }
try { try {
final resp = await postUnauthorized( final resp = await postUnauthorized(
target: credentials.server, target: credentials.server,
path: 'signin', path: 'signin',
body: { body: {
'name': credentials.username, 'name': credentials.username,
'server': credentials.server.tag, 'server': credentials.server.tag,
'accountKey': credentials.password 'accountKey': credentials.password
});
if (resp.res == Result.ok) {
setState(() {
isAuthorized = true;
}); });
} else { if (resp.res == Result.ok) {
// credentials are wrong
// log out
setState(() {
isAuthorized = true;
});
}
} catch (_) {
// user is currently offline
// approve login,
// until user goes back offline
// NOTE TODO: check user data once online
setState(() { setState(() {
isAuthorized = true; isAuthorized = true;
});
} else {
// credentials are wrong
// log out
setState(() {
isAuthorized = true;
}); });
} }
} catch (_) {
// user is currently offline
// approve login,
// until user goes back offline
// NOTE TODO: check user data once online
setState(() {
isAuthorized = true;
});
}
})(); })();
// wait for user to be authorized // wait for user to be authorized
User.listen((data) async { User.listen((data) async {
try { try {
await User.fromDisk(); await User.fromDisk();
setState(() { setState(() {
isAuthorized = true; isAuthorized = true;
}); });
} catch (_) {} } catch (_) {}
}); });
} }
@ -124,8 +122,8 @@ class _OutbagAppState extends State {
theme: ThemeData(useMaterial3: true, brightness: Brightness.light), theme: ThemeData(useMaterial3: true, brightness: Brightness.light),
darkTheme: ThemeData(useMaterial3: true, brightness: Brightness.dark), darkTheme: ThemeData(useMaterial3: true, brightness: Brightness.dark),
routerDelegate: RoutemasterDelegate( routerDelegate: RoutemasterDelegate(
routesBuilder: (context) => routesBuilder: (context) =>
isAuthorized ? routesLoggedIn : routesUnauthorized), isAuthorized ? routesLoggedIn : routesUnauthorized),
routeInformationParser: const RoutemasterParser(), routeInformationParser: const RoutemasterParser(),
); );
} }

View file

@ -1,40 +1,147 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:outbag_app/backend/request.dart';
import 'package:outbag_app/backend/room.dart';
import 'package:outbag_app/backend/user.dart';
import 'package:outbag_app/screens/room/about.dart';
import 'package:outbag_app/screens/room/categories.dart';
import 'package:outbag_app/screens/room/products.dart';
import 'package:outbag_app/screens/room/shopping_list.dart';
import 'package:routemaster/routemaster.dart'; import 'package:routemaster/routemaster.dart';
class RoomPage extends StatefulWidget { class RoomPage extends StatefulWidget {
final String server; final String server;
final String tag; final String tag;
final String page;
const RoomPage(this.server, this.tag, {super.key, this.page="list"}); const RoomPage(this.server, this.tag, {super.key});
@override @override
State<StatefulWidget> createState() => _RoomPageState(); State<StatefulWidget> createState() => _RoomPageState();
} }
class _RoomPageState extends State { class _RoomPageState extends State<RoomPage> {
RoomInfo? info;
Room? room;
final PageController _ctr = PageController(initialPage: 0);
int page = 0;
// fetch room information
void fetchInfo() async {
try {
final diskRoom =
await Room.fromDisk(serverTag: widget.server, id: widget.tag);
setState(() {
room = diskRoom;
});
} catch (_) {}
// fetch additional data from web
User user;
try {
user = await User.fromDisk();
} catch (_) {
// probably not logged in
return;
}
try {
final resp = await postWithCreadentials(
path: 'getRoomInfo',
credentials: user,
target: user.server,
body: {'room': widget.tag, 'server': widget.server});
if (resp.res == Result.ok) {
final info = RoomInfo.fromJSON(resp.body['data']);
final room = Room.fromJSON(resp.body['data']);
setState(() {
this.info = info;
this.room = room;
});
}
} catch (_) {}
}
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// TODO: fetch room data
// from somewhere // schedule info-get
fetchInfo();
_ctr.addListener(() {
setState(() {
page = _ctr.page?.toInt() ?? _ctr.initialPage;
});
});
Room.listen((_) async {
// rooms changed on disk
// probably this one,
// because it is currently open
// NOTE: might be a different room
// (if a background listener is implemented at some point,
// checking if this room changed might improve performance)
try {
final r = await Room.fromDisk(
serverTag: widget.server,
id: widget.tag
);
setState(() {
room = r;
});
} catch (_) {}
});
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text('Room name'), title: Text(room?.name ?? 'Unknown Room'),
leading: IconButton( leading: IconButton(
onPressed: () { onPressed: () {
// go back
Routemaster.of(context).history.back(); Routemaster.of(context).history.back();
}, },
icon: const Icon(Icons.arrow_back), icon: const Icon(Icons.arrow_back),
tooltip: "Go back", tooltip: "Go back",
), ),
), ),
floatingActionButton: FloatingActionButton.extended( body: PageView(
onPressed: () => {}, label: Text('Add'), icon: const Icon(Icons.add)), controller: _ctr,
children: [
ShoppingListPage(room, info),
RoomProductsPage(room, info),
RoomCategoriesPage(room, info),
AboutRoomPage(room, info)
],
),
bottomNavigationBar: NavigationBar(
onDestinationSelected: (int index) {
_ctr.animateToPage(index,
curve: Curves.easeInOut,
duration: const Duration(milliseconds: 300));
},
selectedIndex: page,
destinations: const [
NavigationDestination(
icon: Icon(Icons.list),
label: "List",
tooltip: 'View shopping list'),
NavigationDestination(
icon: Icon(Icons.inventory_2),
label: "Products",
tooltip: 'View saved items'),
NavigationDestination(
icon: Icon(Icons.category),
label: "Categories",
tooltip: 'View categories'),
NavigationDestination(
icon: Icon(Icons.info_rounded),
label: "About",
tooltip: 'View room info'),
],
),
); );
} }
} }

248
lib/screens/room/about.dart Normal file
View file

@ -0,0 +1,248 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:outbag_app/backend/errors.dart';
import 'package:outbag_app/backend/permissions.dart';
import 'package:outbag_app/backend/request.dart';
import 'package:outbag_app/backend/room.dart';
import 'dart:math';
import 'package:outbag_app/backend/user.dart';
import 'package:routemaster/routemaster.dart';
class AboutRoomPage extends StatefulWidget {
final RoomInfo? info;
final Room? room;
const AboutRoomPage(this.room, this.info, {super.key});
@override
State<StatefulWidget> createState() => _AboutRoomPageState();
}
class _AboutRoomPageState extends State<AboutRoomPage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context)
.textTheme
.apply(displayColor: Theme.of(context).colorScheme.onSurface);
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
double smallest = min(width, height);
return Center(
child: Column(children: [
// room meta display
...(widget.room != null)
? [
Padding(
padding: const EdgeInsets.all(14),
child: Column(
children: [
SvgPicture.asset(
(widget.room?.icon?.img)!,
width: smallest * 0.2,
height: smallest * 0.2,
),
Text(
widget.room?.name ?? '',
style: textTheme.displayMedium,
),
Text(
'${widget.room?.id}@${widget.room?.serverTag}',
style: textTheme.bodySmall,
),
Text(widget.room?.description ?? '',
style: textTheme.bodyMedium),
SegmentedButton<int>(
showSelectedIcon: true,
multiSelectionEnabled: false,
emptySelectionAllowed: false,
segments: RoomVisibility.list().map((vis) {
return ButtonSegment<int>(
value: vis.type,
label: Text(vis.text),
icon: Icon(vis.icon));
}).toList(),
onSelectionChanged: ((vset) {
// check permission
// only show confirm dialog when user
// is admin, owner or has CHANGE_ADMIN permission
if (widget.info == null ||
(!(widget.info?.isAdmin ?? false) &&
!(widget.info?.isOwner ?? false) &&
((widget.info?.permissions)! &
RoomPermission.ota ==
0))) {
// action not permitted
// NOTE: no error dialog should be shown
// because the action is supposed to be hidden
return;
}
final vis = RoomVisibility(vset.first);
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Change room visibility'),
content: Text(
'Do you really want to change the room visibility to: ${vis.text}'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Cancel'),
),
FilledButton(
onPressed: () async {
final scaffMgr =
ScaffoldMessenger.of(context);
final nav = Navigator.of(context);
User user;
try {
user = await User.fromDisk();
} catch (_) {
// probably not logged in
nav.pop();
return;
}
try {
final resp =
await postWithCreadentials(
path: 'setVisibility',
target: user.server,
body: {
'room': widget.room?.id,
'server': (widget
.room?.serverTag)!,
'visibility': vset.first
},
credentials: user);
if (resp.res == Result.ok) {
Room r = widget.room!;
r.visibility = vis;
r.toDisk();
} else {
// server error
final snackBar = SnackBar(
behavior:
SnackBarBehavior.floating,
content: Text(
errorAsString(resp.body)),
action: SnackBarAction(
label: 'Dismiss',
onPressed: () {
scaffMgr
.hideCurrentSnackBar();
},
),
);
scaffMgr.hideCurrentSnackBar();
scaffMgr.showSnackBar(snackBar);
}
} catch (e) {
print(e);
// network error
final snackBar = SnackBar(
behavior: SnackBarBehavior.floating,
content:
const Text('Network error'),
action: SnackBarAction(
label: 'Dismiss',
onPressed: () {
scaffMgr.hideCurrentSnackBar();
},
),
);
scaffMgr.hideCurrentSnackBar();
scaffMgr.showSnackBar(snackBar);
}
nav.pop();
},
child: const Text('Ok'),
)
],
));
}),
selected: {(widget.room?.visibility?.type)!},
selectedIcon: Icon((widget.room?.visibility?.icon)!),
),
],
),
)
]
: [],
Padding(
padding: const EdgeInsets.all(14),
child: Column(
children: [
// edit room meta button
...(widget.info != null &&
((widget.info?.isAdmin ?? false) ||
(widget.info?.isOwner ?? false) ||
((widget.info?.permissions)! &
RoomPermission.changeMeta !=
0)))
? [
ListTile(
trailing: const Icon(Icons.chevron_right),
title: const Text('Edit Metadata'),
subtitle: const Text(
'Change the rooms name, description and icon'),
onTap: () {
// TODO: show edit room screen
},
),
]
: [],
// open members view
ListTile(
trailing: const Icon(Icons.chevron_right),
title: const Text('Members'),
subtitle: const Text('Show Member list'),
onTap: () {
// TODO: open member view screen
},
),
...(widget.info != null &&
((widget.info?.isAdmin ?? false) ||
(widget.info?.isOwner ?? false) ||
((widget.info?.permissions)! & RoomPermission.ota !=
0)))
? [
ListTile(
trailing: const Icon(Icons.chevron_right),
title: const Text('OTA'),
subtitle: const Text('Manage and delete OTAs'),
onTap: () {
// TODO: show manage ota screen
},
),
]
: [],
],
)),
Padding(
padding: const EdgeInsets.all(8),
child: FilledButton.tonal(
child: const Text('Leave Room'),
onPressed: () {
// TODO: show confirm dialog
},
))
]));
}
}