Browse Source

Add login and a very simple home page

master
Valentin Anger 3 years ago
parent
commit
381a7745e4
  1. 102
      lib/login.dart
  2. 122
      lib/main.dart
  3. 20
      lib/matrix.dart
  4. 5
      persistant_storage
  5. 2
      pubspec.yaml

102
lib/login.dart

@ -0,0 +1,102 @@
import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginPage extends StatefulWidget {
LoginPage({Key key, this.settings}) : super(key: key);
final SharedPreferences settings;
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final String def_home_server = "https://matrix.org";
String _matrix_id;
String _password;
String _home_server;
String _identity_server;
String _failure_message = "";
void _doLogin() async {
var client = new HttpClient();
await client.postUrl(Uri.parse(_home_server)
.replace(path: "/_matrix/client/r0/login")).then((req) {
req.headers.contentType = new ContentType("application", "json", charset: "utf-8");
var data = new JsonEncoder().convert(<String,dynamic>{
"type": "m.login.password",
"identifier": <String,String>{
"type": "m.id.user",
"user": _matrix_id,
},
"password": _password,
"initial_device_display_name": "Hermes alpha",
});
req.write(data);
return req.close();
}).then((resp) {
return resp.transform(utf8.decoder).join().then((cont) {
var json = new JsonDecoder().convert(cont);
// I hate switch statements
if (resp.statusCode == 403) {
_failure_message = json["error"];
} else if (resp.statusCode == 200) {
var s = widget.settings;
s.setString("access_token", json["access_token"]);
s.setString("matrix_id", json["matrix_id"]);
s.setString("home_server", json["well_known"]["m.homeserver"]["base_url"]);
s.setString("device_id", json["device_id"]);
s.setBool("logged_in", true);
} else {
print(resp.statusCode);
print(json);
}
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Login"),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Matrix ID"),
TextField(autocorrect: false, onChanged: (s) { _matrix_id = s; }),
Text("Password"),
TextField(autocorrect: false, obscureText: true, onChanged: (s) { _password = s; }),
Text("Home server"),
TextField(
autocorrect: false,
controller: TextEditingController(text: def_home_server),
onChanged: (s) { _home_server = s; }
),
Text("Identity server"),
TextField(autocorrect: false, onChanged: (s) { _identity_server = s; }),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(_failure_message),
RaisedButton(
child: Text("Login"),
onPressed: () { setState(() { _doLogin(); }); },
),
],
),
],
),
),
),
);
}
}

122
lib/main.dart

@ -1,111 +1,77 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'login.dart';
import 'matrix.dart';
void main() => runApp(MyApp());
void main() async {
var settings = await SharedPreferences.getInstance();
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
var _home;
if (settings.getBool("logged_in") ?? false) {
_home = MyHomePage(settings: settings);
} else {
_home = LoginPage(settings: settings);
}
runApp(MaterialApp(
title: 'Hermes',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
primarySwatch: Colors.green,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
home: _home,
));
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
MyHomePage({Key key, this.settings}) : super(key: key);
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
final SharedPreferences settings;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
List<String> rooms;
void _addChat() async {
print("Pressed addChat button!");
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
void _updateRooms() {
Matrix.joined_rooms(
widget.settings.getString("home_server"),
widget.settings.getString("access_token")
).then((r) {
setState(() {
rooms = r;
});
});
}
void initState() {
_updateRooms();
super.initState();
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
title: Text("Hermes"),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
child: ListView(
padding: EdgeInsets.all(8.0),
children: rooms.map((s) { return Text(s); }).toList(growable: false),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
onPressed: _addChat,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}

20
lib/matrix.dart

@ -0,0 +1,20 @@
import 'dart:io';
import 'dart:convert';
class Matrix {
// TODO Error handeling
static Future<List<String>> joined_rooms(String server, String access_token) async {
var client = new HttpClient();
return await client.getUrl(Uri.parse(server)
.replace(path: "/_matrix/client/r0/joined_rooms")).then((req) {
req.headers.contentType = new ContentType("application", "json", charset: "utf-8");
req.headers.add("Authorization", "Bearer " + access_token);
return req.close();
}).then((resp) {
return resp.transform(utf8.decoder).join();
}).then((cont) {
var json = new JsonDecoder().convert(cont);
return json["joined_rooms"].cast<String>();
});
}
}

5
persistant_storage

@ -0,0 +1,5 @@
bool logged_in Are we loggen in?
String access_token The access_token
String matrix_id The users matrix id
String home_server The users home server
String device_id Our device id

2
pubspec.yaml

@ -20,6 +20,8 @@ dependencies:
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
shared_preferences: ^0.5.0
dev_dependencies:
flutter_test:
sdk: flutter