💄 Optimized notification page
⬇️ Remove firebase deps
This commit is contained in:
@ -3,8 +3,6 @@ import 'dart:io';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:solaragent/firebase.dart';
|
||||
import 'package:solaragent/preferences.dart';
|
||||
import 'package:solaragent/screens/auth.dart';
|
||||
import 'package:oauth2/oauth2.dart' as oauth2;
|
||||
|
||||
@ -17,10 +15,8 @@ class AuthGuard {
|
||||
Uri.parse('https://id.solsynth.dev/api/notifications/subscribe');
|
||||
final authorizationEndpoint =
|
||||
Uri.parse('https://id.solsynth.dev/auth/o/connect');
|
||||
final tokenEndpoint =
|
||||
Uri.parse('https://id.solsynth.dev/api/auth/token');
|
||||
final userinfoEndpoint =
|
||||
Uri.parse('https://id.solsynth.dev/api/users/me');
|
||||
final tokenEndpoint = Uri.parse('https://id.solsynth.dev/api/auth/token');
|
||||
final userinfoEndpoint = Uri.parse('https://id.solsynth.dev/api/users/me');
|
||||
final redirectUrl = Uri.parse('solaragent://auth');
|
||||
|
||||
static const clientId = "solaragent";
|
||||
@ -42,7 +38,7 @@ class AuthGuard {
|
||||
await pullProfiles();
|
||||
return true;
|
||||
} catch (e) {
|
||||
logout();
|
||||
signoff();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
@ -89,57 +85,41 @@ class AuthGuard {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> login(BuildContext context) async {
|
||||
try {
|
||||
client = await createClient(context);
|
||||
storage.write(key: storageKey, value: client!.credentials.toJson());
|
||||
Future<void> refreshToken() async {
|
||||
if (client != null) {
|
||||
var credentials = await client?.credentials.refresh(
|
||||
identifier: clientId, secret: clientSecret, basicAuth: false);
|
||||
|
||||
await pullProfiles();
|
||||
await subscribeNotify();
|
||||
} catch (e) {
|
||||
print(e);
|
||||
storage.write(key: storageKey, value: credentials!.toJson());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> subscribeNotify() async {
|
||||
if (client == null) {
|
||||
return;
|
||||
}
|
||||
Future<void> signin(BuildContext context) async {
|
||||
client = await createClient(context);
|
||||
storage.write(key: storageKey, value: client!.credentials.toJson());
|
||||
|
||||
var token = await initializeFirebaseMessaging();
|
||||
if (token == null) {
|
||||
print("failed to initialize firebase messaging...");
|
||||
return;
|
||||
}
|
||||
|
||||
var response = await client!.post(
|
||||
deviceEndpoint,
|
||||
headers: {"Content-Type": "application/json"},
|
||||
body: jsonEncode({"device_id": token, "provider": "firebase"}),
|
||||
);
|
||||
if (response.statusCode != 200) {
|
||||
print(response.body);
|
||||
}
|
||||
await pullProfiles();
|
||||
}
|
||||
|
||||
void logout() {
|
||||
try {
|
||||
storage.delete(key: profileKey);
|
||||
storage.delete(key: storageKey);
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
void signoff() {
|
||||
storage.delete(key: profileKey);
|
||||
storage.delete(key: storageKey);
|
||||
}
|
||||
|
||||
Future<bool> isAuthorized() async {
|
||||
const storage = FlutterSecureStorage();
|
||||
return await storage.containsKey(key: storageKey);
|
||||
if (await storage.containsKey(key: storageKey)) {
|
||||
if (client != null && client!.credentials.isExpired) {
|
||||
await refreshToken();
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<dynamic> readProfiles() async {
|
||||
Future<dynamic> getProfiles() async {
|
||||
const storage = FlutterSecureStorage();
|
||||
return jsonDecode(await storage.read(key: profileKey) ?? "{}");
|
||||
}
|
||||
|
||||
AuthGuard._internal();
|
||||
}
|
||||
|
@ -1,43 +0,0 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'firebase_options.dart';
|
||||
|
||||
Future<bool> initializeFirebase() async {
|
||||
await Firebase.initializeApp(
|
||||
options: DefaultFirebaseOptions.currentPlatform,
|
||||
);
|
||||
|
||||
await FirebaseMessaging.instance.requestPermission(
|
||||
alert: true,
|
||||
announcement: false,
|
||||
badge: true,
|
||||
carPlay: false,
|
||||
criticalAlert: false,
|
||||
provisional: false,
|
||||
sound: true,
|
||||
);
|
||||
|
||||
FlutterError.onError = (errorDetails) {
|
||||
FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
|
||||
};
|
||||
PlatformDispatcher.instance.onError = (error, stack) {
|
||||
FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
|
||||
return true;
|
||||
};
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<String?> initializeFirebaseMessaging() async {
|
||||
try {
|
||||
final fcmToken = await FirebaseMessaging.instance.getToken();
|
||||
return fcmToken;
|
||||
} catch (e) {
|
||||
print("failed to setup firebase messaging: $e");
|
||||
return null;
|
||||
}
|
||||
}
|
@ -1,81 +0,0 @@
|
||||
// File generated by FlutterFire CLI.
|
||||
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
|
||||
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
|
||||
import 'package:flutter/foundation.dart'
|
||||
show defaultTargetPlatform, kIsWeb, TargetPlatform;
|
||||
|
||||
/// Default [FirebaseOptions] for use with your Firebase apps.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'firebase_options.dart';
|
||||
/// // ...
|
||||
/// await Firebase.initializeApp(
|
||||
/// options: DefaultFirebaseOptions.currentPlatform,
|
||||
/// );
|
||||
/// ```
|
||||
class DefaultFirebaseOptions {
|
||||
static FirebaseOptions get currentPlatform {
|
||||
if (kIsWeb) {
|
||||
return web;
|
||||
}
|
||||
switch (defaultTargetPlatform) {
|
||||
case TargetPlatform.android:
|
||||
return android;
|
||||
case TargetPlatform.iOS:
|
||||
return ios;
|
||||
case TargetPlatform.macOS:
|
||||
return macos;
|
||||
case TargetPlatform.windows:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for windows - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
case TargetPlatform.linux:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions have not been configured for linux - '
|
||||
'you can reconfigure this by running the FlutterFire CLI again.',
|
||||
);
|
||||
default:
|
||||
throw UnsupportedError(
|
||||
'DefaultFirebaseOptions are not supported for this platform.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static const FirebaseOptions web = FirebaseOptions(
|
||||
apiKey: 'AIzaSyCjTtCsk3Jo98gDiU2Zh8hX2Y-r2CCsT6g',
|
||||
appId: '1:659822066072:web:2fbe2e4dc1186e00c013ed',
|
||||
messagingSenderId: '659822066072',
|
||||
projectId: 'smartsheep-hydrogen',
|
||||
authDomain: 'smartsheep-hydrogen.firebaseapp.com',
|
||||
storageBucket: 'smartsheep-hydrogen.appspot.com',
|
||||
measurementId: 'G-8HVJ5TVQG8',
|
||||
);
|
||||
|
||||
static const FirebaseOptions android = FirebaseOptions(
|
||||
apiKey: 'AIzaSyBLPaAK4CVW9umXIdUoGOGHO42jKnwZkKo',
|
||||
appId: '1:659822066072:android:39e699282c97a7cfc013ed',
|
||||
messagingSenderId: '659822066072',
|
||||
projectId: 'smartsheep-hydrogen',
|
||||
storageBucket: 'smartsheep-hydrogen.appspot.com',
|
||||
);
|
||||
|
||||
static const FirebaseOptions ios = FirebaseOptions(
|
||||
apiKey: 'AIzaSyBQB4u2KKe1P5jMG_zWGiUFtpcjQKhG3jY',
|
||||
appId: '1:659822066072:ios:90dff099ef47fc8fc013ed',
|
||||
messagingSenderId: '659822066072',
|
||||
projectId: 'smartsheep-hydrogen',
|
||||
storageBucket: 'smartsheep-hydrogen.appspot.com',
|
||||
iosBundleId: 'dev.solsynth.solaragent',
|
||||
);
|
||||
|
||||
static const FirebaseOptions macos = FirebaseOptions(
|
||||
apiKey: 'AIzaSyBQB4u2KKe1P5jMG_zWGiUFtpcjQKhG3jY',
|
||||
appId: '1:659822066072:ios:17efa96a78467043c013ed',
|
||||
messagingSenderId: '659822066072',
|
||||
projectId: 'smartsheep-hydrogen',
|
||||
storageBucket: 'smartsheep-hydrogen.appspot.com',
|
||||
iosBundleId: 'dev.solsynth.solaragent.RunnerTests',
|
||||
);
|
||||
}
|
@ -1,18 +1,11 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:solaragent/auth.dart';
|
||||
import 'package:solaragent/firebase.dart';
|
||||
import 'package:solaragent/router.dart';
|
||||
import 'package:solaragent/widgets/navigation.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
try {
|
||||
await initializeFirebase();
|
||||
} catch (e) {
|
||||
print(e);
|
||||
}
|
||||
|
||||
await authClient.pickClient();
|
||||
|
||||
runApp(const SolarAgent());
|
||||
|
@ -18,8 +18,8 @@ class AboutScreen extends StatelessWidget {
|
||||
children: [
|
||||
Text('SolarAgent',
|
||||
style: Theme.of(context).textTheme.headlineMedium),
|
||||
Text('Solarworks Official Mobile Helper',
|
||||
style: Theme.of(context).textTheme.bodyLarge),
|
||||
Text('Solar Networks Official Mobile Application',
|
||||
style: Theme.of(context).textTheme.bodyMedium),
|
||||
const SizedBox(height: 20),
|
||||
FutureBuilder(
|
||||
future: PackageInfo.fromPlatform(),
|
||||
|
@ -35,7 +35,7 @@ class _AccountScreenState extends State<AccountScreen> {
|
||||
padding: const EdgeInsets.only(top: 20),
|
||||
child: NameCard(
|
||||
onLogin: () async {
|
||||
await authClient.login(context);
|
||||
await authClient.signin(context);
|
||||
var authorized = await authClient.isAuthorized();
|
||||
setState(() {
|
||||
isAuthorized = authorized;
|
||||
@ -58,7 +58,7 @@ class _AccountScreenState extends State<AccountScreen> {
|
||||
const BorderRadius.all(Radius.circular(40)),
|
||||
splashColor: Colors.indigo.withAlpha(30),
|
||||
onTap: () async {
|
||||
authClient.logout();
|
||||
authClient.signoff();
|
||||
var authorized =
|
||||
await authClient.isAuthorized();
|
||||
setState(() {
|
||||
|
@ -1,6 +1,8 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:solaragent/auth.dart';
|
||||
|
||||
class NotificationScreen extends StatefulWidget {
|
||||
@ -11,32 +13,32 @@ class NotificationScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _NotificationScreenState extends State<NotificationScreen> {
|
||||
final notificationEndpoint = Uri.parse(
|
||||
'https://id.solsynth.dev/api/notifications?skip=0&take=25');
|
||||
final notificationEndpoint =
|
||||
Uri.parse('https://id.solsynth.dev/api/notifications?skip=0&take=25');
|
||||
|
||||
List<dynamic> notifications = List.empty();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_pullNotifications();
|
||||
pullNotifications();
|
||||
}
|
||||
|
||||
Future<void> _pullNotifications() async {
|
||||
Future<void> pullNotifications() async {
|
||||
if (await authClient.isAuthorized()) {
|
||||
await authClient.pullProfiles();
|
||||
var profiles = await authClient.readProfiles();
|
||||
setState(() {
|
||||
notifications = profiles['notifications'];
|
||||
});
|
||||
var res = await authClient.client!.get(notificationEndpoint);
|
||||
if (res.statusCode == 200) {
|
||||
setState(() {
|
||||
notifications = jsonDecode(utf8.decode(res.bodyBytes))["data"];
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _markAsRead(element) async {
|
||||
Future<void> markAsRead(element) async {
|
||||
if (authClient.client != null) {
|
||||
var id = element['id'];
|
||||
var uri =
|
||||
Uri.parse('https://id.solsynth.dev/api/notifications/$id/read');
|
||||
var uri = Uri.parse('https://id.solsynth.dev/api/notifications/$id/read');
|
||||
await authClient.client!.put(uri);
|
||||
}
|
||||
}
|
||||
@ -45,49 +47,92 @@ class _NotificationScreenState extends State<NotificationScreen> {
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 20, right: 20, top: 30),
|
||||
child: RefreshIndicator(
|
||||
onRefresh: _pullNotifications,
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
notifications.isEmpty
|
||||
? const SliverToBoxAdapter(
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(10),
|
||||
child: ListTile(
|
||||
leading: Icon(Icons.check),
|
||||
title: Text('You\'re done!'),
|
||||
subtitle: Text(
|
||||
'There are no notifications unread for you.'),
|
||||
),
|
||||
child: RefreshIndicator(
|
||||
onRefresh: pullNotifications,
|
||||
child: CustomScrollView(
|
||||
slivers: [
|
||||
// Title
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 10, right: 10, top: 20),
|
||||
child: ListTile(
|
||||
title: Text(
|
||||
'Notifications',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Content
|
||||
notifications.isEmpty
|
||||
? SliverToBoxAdapter(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||
color: Colors.grey[300],
|
||||
child: const ListTile(
|
||||
leading: Icon(Icons.check),
|
||||
title: Text('You\'re done!'),
|
||||
subtitle: Text(
|
||||
'There are no notifications unread for you.',
|
||||
),
|
||||
),
|
||||
)
|
||||
: SliverList.builder(
|
||||
itemCount: notifications.length,
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
var element = notifications[index];
|
||||
return Dismissible(
|
||||
key: Key('notification-$index'),
|
||||
onDismissed: (direction) {
|
||||
var subject = element["subject"];
|
||||
_markAsRead(element).then((value) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content:
|
||||
Text('「$subject」 mark as read')));
|
||||
});
|
||||
},
|
||||
child: ListTile(
|
||||
title: Text(element["subject"]),
|
||||
subtitle: Text(element["content"]),
|
||||
));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: SliverList.builder(
|
||||
itemCount: notifications.length,
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
var element = notifications[index];
|
||||
return Dismissible(
|
||||
key: Key('notification-$index'),
|
||||
onDismissed: (direction) {
|
||||
var subject = element["subject"];
|
||||
markAsRead(element).then((value) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: RichText(
|
||||
text: TextSpan(children: [
|
||||
TextSpan(
|
||||
text: subject,
|
||||
style: const TextStyle(
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const TextSpan(
|
||||
text: " is marked as read",
|
||||
)
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
setState(() {
|
||||
notifications.removeAt(index);
|
||||
});
|
||||
},
|
||||
background: Container(
|
||||
color: Colors.green,
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10),
|
||||
child: ListTile(
|
||||
title: Text(element["subject"]),
|
||||
subtitle: Text(element["content"]),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
// Tips
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 10),
|
||||
child: Text(
|
||||
"Pull to refresh, swipe to dismiss",
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
|
@ -13,7 +13,7 @@ class NameCard extends StatelessWidget {
|
||||
|
||||
Future<CircleAvatar> _getAvatar() async {
|
||||
if (await authClient.isAuthorized()) {
|
||||
final profiles = await authClient.readProfiles();
|
||||
final profiles = await authClient.getProfiles();
|
||||
return CircleAvatar(backgroundImage: NetworkImage(profiles["picture"]));
|
||||
} else {
|
||||
return const CircleAvatar(child: Icon(Icons.account_circle));
|
||||
@ -22,7 +22,7 @@ class NameCard extends StatelessWidget {
|
||||
|
||||
Future<Column> _getDescribe() async {
|
||||
if (await authClient.isAuthorized()) {
|
||||
final profiles = await authClient.readProfiles();
|
||||
final profiles = await authClient.getProfiles();
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
|
Reference in New Issue
Block a user