Skip to content

Changes: User and Enigma #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Developers extends StatefulWidget {
}

class _DevelopersState extends State<Developers> {
Session selectedSession = Session.session_22_23;
Session selectedSession = Session.session_23_24;
Map members = {};

Widget positionHeading(BuildContext ctx, String title) {
Expand Down
5 changes: 0 additions & 5 deletions lib/screens/home_screen/pages/EventsPage/events_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,6 @@ class _EventsPageState extends State<EventsPage> {
builder: (context) => const EnigmaPage(),
),
);
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => engima_page(),
// ));
},
child: Card(
shape: RoundedRectangleBorder(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ class _EnigmaEventState extends State<EnigmaEvent> {
final now = DateTime.now();

for (final event in events) {
final startDate = DateTime.parse(event?["startDate"] ??
'');
final startDate = DateTime.parse(event?["startDate"] ?? '');
final durationInHrs = event?["durationInHrs"] as int?;

if (durationInHrs != null) {
Expand All @@ -72,7 +71,7 @@ class _EnigmaEventState extends State<EnigmaEvent> {

Widget _buildSection(String title, List<dynamic>? events) {
if (events == null || events.isEmpty) {
return SizedBox();
return const SizedBox();
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
Expand All @@ -91,7 +90,7 @@ class _EnigmaEventState extends State<EnigmaEvent> {
itemCount: eventdetails.length,
itemBuilder: (context, int index) {
if (eventdetails[index] == null || eventdetails.isEmpty) {
return SizedBox();
return const SizedBox();
}
return Container(
width: MediaQuery.of(context).size.width * 0.6,
Expand Down Expand Up @@ -145,35 +144,12 @@ class _EnigmaEventState extends State<EnigmaEvent> {
msg: "Contest link copied to clipboard");
}
},
onPressed: () async {
if (!Provider.of<UserHandler>(context,
listen: false)
.user!
.registeredEnigmas
.contains(
eventdetails[index]!['_id'].toString())) {
setState(() {
isLoading = true;
});
Response res = await Provider.of<UserHandler>(
context,
listen: false)
.registerEnigma(eventdetails[index]['_id']);

if ((res.statusCode ?? 400) >= 200 &&
(res.statusCode ?? 400) < 300) {
Fluttertoast.showToast(
msg: res.data['error'] ?? 'Unknown Error');
}
} else {
launchUrl(
Uri.parse(
eventdetails[index]!["cfContestLink"]),
mode: LaunchMode.externalApplication);
}
setState(() {
isLoading = false;
});
onPressed: () {
launchUrl(
Uri.parse(eventdetails[index]!["cfContestLink"]),
//If you want to launch in external app and not in CSS
// mode: LaunchMode.externalApplication
);
},
child: Text(
Provider.of<UserHandler>(context)
Expand All @@ -185,6 +161,64 @@ class _EnigmaEventState extends State<EnigmaEvent> {
: "Register Here",
),
),
Provider.of<UserHandler>(context)
.user!
.registeredEnigmas
.contains(
eventdetails[index]!['_id'].toString())
? const Padding(
padding: EdgeInsets.all(8.0),
child: Text("Already registered"),
)
: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Flexible(
child: Text("Have you registered?")),
Flexible(
child: ElevatedButton(
onPressed: () async {
if (!Provider.of<UserHandler>(context,
listen: false)
.user!
.registeredEnigmas
.contains(
eventdetails[index]!['_id']
.toString())) {
setState(() {
isLoading = true;
});
Response res = await Provider.of<
UserHandler>(context,
listen: false)
.registerEnigma(
eventdetails[index]['_id']);

if ((res.statusCode ?? 400) >=
200 &&
(res.statusCode ?? 400) < 300) {
Fluttertoast.showToast(
msg: res.data['error'] ??
'Unknown Error');
}
}
setState(() {
isLoading = false;
});
},
child: const Text("Yes")),
),
Flexible(
child: ElevatedButton(
onPressed: () {
Fluttertoast.showToast(
msg:
"Please register for the contest");
},
child: const Text("No")),
)
],
),
],
),
);
Expand All @@ -202,7 +236,7 @@ class _EnigmaEventState extends State<EnigmaEvent> {
eventdetails = snapshot.data;

if (eventdetails.isEmpty) {
return Center(
return const Center(
child: Text(
'No events available')); // Handle null or empty eventdetails
}
Expand All @@ -229,19 +263,19 @@ class _EnigmaEventState extends State<EnigmaEvent> {
Tab(
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.33,
child: Center(child: Text('Live')),
child: const Center(child: Text('Live')),
),
),
Tab(
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.33,
child: Center(child: Text('Upcoming')),
child: const Center(child: Text('Upcoming')),
),
),
Tab(
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.33,
child: Center(child: Text('Past')),
child: const Center(child: Text('Past')),
),
),
],
Expand Down
4 changes: 4 additions & 0 deletions lib/splash.dart
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ class _SplashState extends State<Splash> {
} else {
Provider.of<MemberApi>(context, listen: false).isOnline = false;
Fluttertoast.showToast(msg: "Couldn't connect to the internet");
// Fetching user from local storage in case of no internet
if (await NetworkEngine.doesCookieDirExists()) {
await Provider.of<UserHandler>(context, listen: false).fetchUser();
}
}
Widget page = const AuthScreen();
if (Provider.of<UserHandler>(context, listen: false).user != null) {
Expand Down
6 changes: 6 additions & 0 deletions lib/state_handlers/user/user_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'user_model.dart';
import 'package:cssapp/utils/network_engine.dart';
import 'package:cssapp/utils/storage_handler.dart';

class UserHandler extends ChangeNotifier {
UserModel? user;
Expand Down Expand Up @@ -54,6 +55,8 @@ class UserHandler extends ChangeNotifier {

if ((res.statusCode ?? 400) >= 200 && (res.statusCode ?? 400) < 300) {
user = UserModel.read(res.data);
// Storing user details in local storage on successful login
StorageHandler().saveUserToLocalStorage(user!);
}
return res;
}
Expand All @@ -66,6 +69,9 @@ class UserHandler extends ChangeNotifier {
(res.statusCode ?? 400) < 300 &&
res.data?['user'] != null) {
user = UserModel.read(res.data);
} else {
// Loading user from local storage
user = await StorageHandler().loadUserFromLocalStorage();
}
return res;
}
Expand Down
35 changes: 35 additions & 0 deletions lib/state_handlers/user/user_model.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:convert';

class UserModel {
String name;
String email;
Expand Down Expand Up @@ -29,4 +31,37 @@ class UserModel {
List<String>.from(data['registeredAbacusEvents']),
registeredEnigmas: List<String>.from(data['registeredEnigmas']));
}

// Convert UserModel to a Map
Map<String, dynamic> toMap() {
return {
'name': name,
'email': email,
'scholarID': scholarID,
'codeforcesHandle': codeforcesHandle,
'githubHandle': githubHandle,
'registeredAbacusEvents': registeredAbacusEvents,
'registeredEnigmas': registeredEnigmas,
};
}

// Create a UserModel from a Map
factory UserModel.fromMap(Map<String, dynamic> map) {
return UserModel(
name: map['name'],
email: map['email'],
scholarID: map['scholarID'],
codeforcesHandle: map['codeforcesHandle'],
githubHandle: map['githubHandle'],
registeredAbacusEvents: List<String>.from(map['registeredAbacusEvents']),
registeredEnigmas: List<String>.from(map['registeredEnigmas']),
);
}

// Convert UserModel to a JSON string
String toJson() => json.encode(toMap());

// Create a UserModel from a JSON string
factory UserModel.fromJson(String source) =>
UserModel.fromMap(json.decode(source));
}
3 changes: 3 additions & 0 deletions lib/utils/network_engine.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:io';

import 'package:cssapp/utils/storage_handler.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
Expand All @@ -26,6 +27,8 @@ class NetworkEngine {
}

static Future<void> signOut() async {
// Delete all user data from local storage on logout
StorageHandler().clearAllData();
final Directory appDocDir = await getApplicationDocumentsDirectory();
Directory cookiesDir = Directory(appDocDir.path + _cookieDirName);
if (await cookiesDir.exists()) {
Expand Down
18 changes: 18 additions & 0 deletions lib/utils/storage_handler.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// ignore_for_file: avoid_print

import 'dart:ui';
import 'package:cssapp/state_handlers/user/user_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

class StorageHandler {
Expand All @@ -12,11 +13,28 @@ class StorageHandler {
PlatformDispatcher.instance.platformBrightness == Brightness.dark;
}

Future<UserModel?> loadUserFromLocalStorage() async {
final jsonString = _preferences?.getString('user');
if (jsonString != null) {
return UserModel.fromJson(jsonString);
} else {
return null;
}
}

// ----------------------------- Setter Methods -----------------------------
Future<void> toggleDarkTheme() async {
await _preferences?.setBool('isDarkTheme', !isDarkTheme());
}

Future<void> saveUserToLocalStorage(UserModel user) async {
await _preferences?.setString('user', user.toJson());
}

Future<void> clearAllData() async {
await _preferences?.clear();
}

Future<void> initPreferences() async {
_preferences = await SharedPreferences.getInstance();
}
Expand Down
Loading