From c9736cb738d9c35f3d2c6064d0fb0e5c51649975 Mon Sep 17 00:00:00 2001 From: Erick Date: Thu, 26 Dec 2024 11:52:30 +0300 Subject: [PATCH] fix: courses page stuck on loading state on app restart --- lib/database/database.g.dart | 307 ++++++++++++++---- .../auth/repository/user_repository.dart | 14 +- lib/features/courses/cubit/course_cubit.dart | 15 +- lib/features/courses/models/course.dart | 5 +- .../repository/course_local_repository.dart | 4 +- .../courses/repository/course_repository.dart | 13 +- .../courses/views/courses_page_mobile.dart | 8 +- 7 files changed, 279 insertions(+), 87 deletions(-) diff --git a/lib/database/database.g.dart b/lib/database/database.g.dart index 092b45e..dd699cb 100644 --- a/lib/database/database.g.dart +++ b/lib/database/database.g.dart @@ -1501,16 +1501,19 @@ class $CourseTable extends Course with TableInfo<$CourseTable, CourseData> { final GeneratedDatabase attachedDatabase; final String? _alias; $CourseTable(this.attachedDatabase, [this._alias]); - static const VerificationMeta _idMeta = const VerificationMeta('id'); - @override - late final GeneratedColumn id = GeneratedColumn( - 'id', aliasedName, true, - type: DriftSqlType.string, requiredDuringInsert: false); static const VerificationMeta _unitMeta = const VerificationMeta('unit'); @override late final GeneratedColumn unit = GeneratedColumn( 'unit', aliasedName, false, type: DriftSqlType.string, requiredDuringInsert: true); + static const VerificationMeta _userMeta = const VerificationMeta('user'); + @override + late final GeneratedColumn user = GeneratedColumn( + 'user', aliasedName, true, + type: DriftSqlType.string, + requiredDuringInsert: false, + defaultConstraints: + GeneratedColumn.constraintIsAlways('REFERENCES user (id)')); static const VerificationMeta _sectionMeta = const VerificationMeta('section'); @override @@ -1559,8 +1562,8 @@ class $CourseTable extends Course with TableInfo<$CourseTable, CourseData> { defaultValue: Constant(DateTime.now())); @override List get $columns => [ - id, unit, + user, section, weekDay, campus, @@ -1580,15 +1583,16 @@ class $CourseTable extends Course with TableInfo<$CourseTable, CourseData> { {bool isInserting = false}) { final context = VerificationContext(); final data = instance.toColumns(true); - if (data.containsKey('id')) { - context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); - } if (data.containsKey('unit')) { context.handle( _unitMeta, unit.isAcceptableOrUnknown(data['unit']!, _unitMeta)); } else if (isInserting) { context.missing(_unitMeta); } + if (data.containsKey('user')) { + context.handle( + _userMeta, user.isAcceptableOrUnknown(data['user']!, _userMeta)); + } if (data.containsKey('section')) { context.handle(_sectionMeta, section.isAcceptableOrUnknown(data['section']!, _sectionMeta)); @@ -1637,15 +1641,15 @@ class $CourseTable extends Course with TableInfo<$CourseTable, CourseData> { } @override - Set get $primaryKey => {id}; + Set get $primaryKey => {unit}; @override CourseData map(Map data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return CourseData( - id: attachedDatabase.typeMapping - .read(DriftSqlType.string, data['${effectivePrefix}id']), unit: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}unit'])!, + user: attachedDatabase.typeMapping + .read(DriftSqlType.string, data['${effectivePrefix}user']), section: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}section'])!, weekDay: attachedDatabase.typeMapping @@ -1672,8 +1676,8 @@ class $CourseTable extends Course with TableInfo<$CourseTable, CourseData> { } class CourseData extends DataClass implements Insertable { - final String? id; final String unit; + final String? user; final String section; final String weekDay; final String campus; @@ -1683,8 +1687,8 @@ class CourseData extends DataClass implements Insertable { final int? color; final DateTime? createdAt; const CourseData( - {this.id, - required this.unit, + {required this.unit, + this.user, required this.section, required this.weekDay, required this.campus, @@ -1696,10 +1700,10 @@ class CourseData extends DataClass implements Insertable { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (!nullToAbsent || id != null) { - map['id'] = Variable(id); - } map['unit'] = Variable(unit); + if (!nullToAbsent || user != null) { + map['user'] = Variable(user); + } map['section'] = Variable(section); map['week_day'] = Variable(weekDay); map['campus'] = Variable(campus); @@ -1717,8 +1721,8 @@ class CourseData extends DataClass implements Insertable { CourseCompanion toCompanion(bool nullToAbsent) { return CourseCompanion( - id: id == null && nullToAbsent ? const Value.absent() : Value(id), unit: Value(unit), + user: user == null && nullToAbsent ? const Value.absent() : Value(user), section: Value(section), weekDay: Value(weekDay), campus: Value(campus), @@ -1737,8 +1741,8 @@ class CourseData extends DataClass implements Insertable { {ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return CourseData( - id: serializer.fromJson(json['id']), unit: serializer.fromJson(json['unit']), + user: serializer.fromJson(json['user']), section: serializer.fromJson(json['section']), weekDay: serializer.fromJson(json['day_of_the_week']), campus: serializer.fromJson(json['campus']), @@ -1753,8 +1757,8 @@ class CourseData extends DataClass implements Insertable { Map toJson({ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return { - 'id': serializer.toJson(id), 'unit': serializer.toJson(unit), + 'user': serializer.toJson(user), 'section': serializer.toJson(section), 'day_of_the_week': serializer.toJson(weekDay), 'campus': serializer.toJson(campus), @@ -1767,8 +1771,8 @@ class CourseData extends DataClass implements Insertable { } CourseData copyWith( - {Value id = const Value.absent(), - String? unit, + {String? unit, + Value user = const Value.absent(), String? section, String? weekDay, String? campus, @@ -1778,8 +1782,8 @@ class CourseData extends DataClass implements Insertable { Value color = const Value.absent(), Value createdAt = const Value.absent()}) => CourseData( - id: id.present ? id.value : this.id, unit: unit ?? this.unit, + user: user.present ? user.value : this.user, section: section ?? this.section, weekDay: weekDay ?? this.weekDay, campus: campus ?? this.campus, @@ -1791,8 +1795,8 @@ class CourseData extends DataClass implements Insertable { ); CourseData copyWithCompanion(CourseCompanion data) { return CourseData( - id: data.id.present ? data.id.value : this.id, unit: data.unit.present ? data.unit.value : this.unit, + user: data.user.present ? data.user.value : this.user, section: data.section.present ? data.section.value : this.section, weekDay: data.weekDay.present ? data.weekDay.value : this.weekDay, campus: data.campus.present ? data.campus.value : this.campus, @@ -1807,8 +1811,8 @@ class CourseData extends DataClass implements Insertable { @override String toString() { return (StringBuffer('CourseData(') - ..write('id: $id, ') ..write('unit: $unit, ') + ..write('user: $user, ') ..write('section: $section, ') ..write('weekDay: $weekDay, ') ..write('campus: $campus, ') @@ -1822,14 +1826,14 @@ class CourseData extends DataClass implements Insertable { } @override - int get hashCode => Object.hash(id, unit, section, weekDay, campus, room, + int get hashCode => Object.hash(unit, user, section, weekDay, campus, room, lecturer, period, color, createdAt); @override bool operator ==(Object other) => identical(this, other) || (other is CourseData && - other.id == this.id && other.unit == this.unit && + other.user == this.user && other.section == this.section && other.weekDay == this.weekDay && other.campus == this.campus && @@ -1841,8 +1845,8 @@ class CourseData extends DataClass implements Insertable { } class CourseCompanion extends UpdateCompanion { - final Value id; final Value unit; + final Value user; final Value section; final Value weekDay; final Value campus; @@ -1853,8 +1857,8 @@ class CourseCompanion extends UpdateCompanion { final Value createdAt; final Value rowid; const CourseCompanion({ - this.id = const Value.absent(), this.unit = const Value.absent(), + this.user = const Value.absent(), this.section = const Value.absent(), this.weekDay = const Value.absent(), this.campus = const Value.absent(), @@ -1866,8 +1870,8 @@ class CourseCompanion extends UpdateCompanion { this.rowid = const Value.absent(), }); CourseCompanion.insert({ - this.id = const Value.absent(), required String unit, + this.user = const Value.absent(), required String section, required String weekDay, required String campus, @@ -1885,8 +1889,8 @@ class CourseCompanion extends UpdateCompanion { lecturer = Value(lecturer), period = Value(period); static Insertable custom({ - Expression? id, Expression? unit, + Expression? user, Expression? section, Expression? weekDay, Expression? campus, @@ -1898,8 +1902,8 @@ class CourseCompanion extends UpdateCompanion { Expression? rowid, }) { return RawValuesInsertable({ - if (id != null) 'id': id, if (unit != null) 'unit': unit, + if (user != null) 'user': user, if (section != null) 'section': section, if (weekDay != null) 'week_day': weekDay, if (campus != null) 'campus': campus, @@ -1913,8 +1917,8 @@ class CourseCompanion extends UpdateCompanion { } CourseCompanion copyWith( - {Value? id, - Value? unit, + {Value? unit, + Value? user, Value? section, Value? weekDay, Value? campus, @@ -1925,8 +1929,8 @@ class CourseCompanion extends UpdateCompanion { Value? createdAt, Value? rowid}) { return CourseCompanion( - id: id ?? this.id, unit: unit ?? this.unit, + user: user ?? this.user, section: section ?? this.section, weekDay: weekDay ?? this.weekDay, campus: campus ?? this.campus, @@ -1942,12 +1946,12 @@ class CourseCompanion extends UpdateCompanion { @override Map toColumns(bool nullToAbsent) { final map = {}; - if (id.present) { - map['id'] = Variable(id.value); - } if (unit.present) { map['unit'] = Variable(unit.value); } + if (user.present) { + map['user'] = Variable(user.value); + } if (section.present) { map['section'] = Variable(section.value); } @@ -1981,8 +1985,8 @@ class CourseCompanion extends UpdateCompanion { @override String toString() { return (StringBuffer('CourseCompanion(') - ..write('id: $id, ') ..write('unit: $unit, ') + ..write('user: $user, ') ..write('section: $section, ') ..write('weekDay: $weekDay, ') ..write('campus: $campus, ') @@ -2061,6 +2065,20 @@ final class $$UserTableReferences return ProcessedTableManager( manager.$state.copyWith(prefetchedData: cache)); } + + static MultiTypedResultKey<$CourseTable, List> _courseRefsTable( + _$AppDatabase db) => + MultiTypedResultKey.fromTable(db.course, + aliasName: $_aliasNameGenerator(db.user.id, db.course.user)); + + $$CourseTableProcessedTableManager get courseRefs { + final manager = $$CourseTableTableManager($_db, $_db.course) + .filter((f) => f.user.id($_item.id)); + + final cache = $_typedResult.readTableOrNull(_courseRefsTable($_db)); + return ProcessedTableManager( + manager.$state.copyWith(prefetchedData: cache)); + } } class $$UserTableFilterComposer extends Composer<_$AppDatabase, $UserTable> { @@ -2124,6 +2142,27 @@ class $$UserTableFilterComposer extends Composer<_$AppDatabase, $UserTable> { )); return f(composer); } + + Expression courseRefs( + Expression Function($$CourseTableFilterComposer f) f) { + final $$CourseTableFilterComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.id, + referencedTable: $db.course, + getReferencedColumn: (t) => t.user, + builder: (joinBuilder, + {$addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer}) => + $$CourseTableFilterComposer( + $db: $db, + $table: $db.course, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: + $removeJoinBuilderFromRootComposer, + )); + return f(composer); + } } class $$UserTableOrderingComposer extends Composer<_$AppDatabase, $UserTable> { @@ -2230,6 +2269,27 @@ class $$UserTableAnnotationComposer )); return f(composer); } + + Expression courseRefs( + Expression Function($$CourseTableAnnotationComposer a) f) { + final $$CourseTableAnnotationComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.id, + referencedTable: $db.course, + getReferencedColumn: (t) => t.user, + builder: (joinBuilder, + {$addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer}) => + $$CourseTableAnnotationComposer( + $db: $db, + $table: $db.course, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: + $removeJoinBuilderFromRootComposer, + )); + return f(composer); + } } class $$UserTableTableManager extends RootTableManager< @@ -2243,7 +2303,7 @@ class $$UserTableTableManager extends RootTableManager< $$UserTableUpdateCompanionBuilder, (UserData, $$UserTableReferences), UserData, - PrefetchHooks Function({bool userProfileRefs})> { + PrefetchHooks Function({bool userProfileRefs, bool courseRefs})> { $$UserTableTableManager(_$AppDatabase db, $UserTable table) : super(TableManagerState( db: db, @@ -2314,10 +2374,14 @@ class $$UserTableTableManager extends RootTableManager< .map((e) => (e.readTable(table), $$UserTableReferences(db, table, e))) .toList(), - prefetchHooksCallback: ({userProfileRefs = false}) { + prefetchHooksCallback: ( + {userProfileRefs = false, courseRefs = false}) { return PrefetchHooks( db: db, - explicitlyWatchedTables: [if (userProfileRefs) db.userProfile], + explicitlyWatchedTables: [ + if (userProfileRefs) db.userProfile, + if (courseRefs) db.course + ], addJoins: null, getPrefetchedDataCallback: (items) async { return [ @@ -2332,6 +2396,17 @@ class $$UserTableTableManager extends RootTableManager< referencedItemsForCurrentItem: (item, referencedItems) => referencedItems.where((e) => e.userId == item.id), + typedResults: items), + if (courseRefs) + await $_getPrefetchedData( + currentTable: table, + referencedTable: + $$UserTableReferences._courseRefsTable(db), + managerFromTypedResult: (p0) => + $$UserTableReferences(db, table, p0).courseRefs, + referencedItemsForCurrentItem: + (item, referencedItems) => + referencedItems.where((e) => e.user == item.id), typedResults: items) ]; }, @@ -2351,7 +2426,7 @@ typedef $$UserTableProcessedTableManager = ProcessedTableManager< $$UserTableUpdateCompanionBuilder, (UserData, $$UserTableReferences), UserData, - PrefetchHooks Function({bool userProfileRefs})>; + PrefetchHooks Function({bool userProfileRefs, bool courseRefs})>; typedef $$UserProfileTableCreateCompanionBuilder = UserProfileCompanion Function({ required String userId, @@ -3160,8 +3235,8 @@ typedef $$UserCredentialTableProcessedTableManager = ProcessedTableManager< UserCredentialData, PrefetchHooks Function({bool userId, bool username, bool email})>; typedef $$CourseTableCreateCompanionBuilder = CourseCompanion Function({ - Value id, required String unit, + Value user, required String section, required String weekDay, required String campus, @@ -3173,8 +3248,8 @@ typedef $$CourseTableCreateCompanionBuilder = CourseCompanion Function({ Value rowid, }); typedef $$CourseTableUpdateCompanionBuilder = CourseCompanion Function({ - Value id, Value unit, + Value user, Value section, Value weekDay, Value campus, @@ -3186,6 +3261,24 @@ typedef $$CourseTableUpdateCompanionBuilder = CourseCompanion Function({ Value rowid, }); +final class $$CourseTableReferences + extends BaseReferences<_$AppDatabase, $CourseTable, CourseData> { + $$CourseTableReferences(super.$_db, super.$_table, super.$_typedResult); + + static $UserTable _userTable(_$AppDatabase db) => + db.user.createAlias($_aliasNameGenerator(db.course.user, db.user.id)); + + $$UserTableProcessedTableManager? get user { + if ($_item.user == null) return null; + final manager = $$UserTableTableManager($_db, $_db.user) + .filter((f) => f.id($_item.user!)); + final item = $_typedResult.readTableOrNull(_userTable($_db)); + if (item == null) return manager; + return ProcessedTableManager( + manager.$state.copyWith(prefetchedData: [item])); + } +} + class $$CourseTableFilterComposer extends Composer<_$AppDatabase, $CourseTable> { $$CourseTableFilterComposer({ @@ -3195,9 +3288,6 @@ class $$CourseTableFilterComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnFilters get id => $composableBuilder( - column: $table.id, builder: (column) => ColumnFilters(column)); - ColumnFilters get unit => $composableBuilder( column: $table.unit, builder: (column) => ColumnFilters(column)); @@ -3224,6 +3314,26 @@ class $$CourseTableFilterComposer ColumnFilters get createdAt => $composableBuilder( column: $table.createdAt, builder: (column) => ColumnFilters(column)); + + $$UserTableFilterComposer get user { + final $$UserTableFilterComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.user, + referencedTable: $db.user, + getReferencedColumn: (t) => t.id, + builder: (joinBuilder, + {$addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer}) => + $$UserTableFilterComposer( + $db: $db, + $table: $db.user, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: + $removeJoinBuilderFromRootComposer, + )); + return composer; + } } class $$CourseTableOrderingComposer @@ -3235,9 +3345,6 @@ class $$CourseTableOrderingComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - ColumnOrderings get id => $composableBuilder( - column: $table.id, builder: (column) => ColumnOrderings(column)); - ColumnOrderings get unit => $composableBuilder( column: $table.unit, builder: (column) => ColumnOrderings(column)); @@ -3264,6 +3371,26 @@ class $$CourseTableOrderingComposer ColumnOrderings get createdAt => $composableBuilder( column: $table.createdAt, builder: (column) => ColumnOrderings(column)); + + $$UserTableOrderingComposer get user { + final $$UserTableOrderingComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.user, + referencedTable: $db.user, + getReferencedColumn: (t) => t.id, + builder: (joinBuilder, + {$addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer}) => + $$UserTableOrderingComposer( + $db: $db, + $table: $db.user, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: + $removeJoinBuilderFromRootComposer, + )); + return composer; + } } class $$CourseTableAnnotationComposer @@ -3275,9 +3402,6 @@ class $$CourseTableAnnotationComposer super.$addJoinBuilderToRootComposer, super.$removeJoinBuilderFromRootComposer, }); - GeneratedColumn get id => - $composableBuilder(column: $table.id, builder: (column) => column); - GeneratedColumn get unit => $composableBuilder(column: $table.unit, builder: (column) => column); @@ -3304,6 +3428,26 @@ class $$CourseTableAnnotationComposer GeneratedColumn get createdAt => $composableBuilder(column: $table.createdAt, builder: (column) => column); + + $$UserTableAnnotationComposer get user { + final $$UserTableAnnotationComposer composer = $composerBuilder( + composer: this, + getCurrentColumn: (t) => t.user, + referencedTable: $db.user, + getReferencedColumn: (t) => t.id, + builder: (joinBuilder, + {$addJoinBuilderToRootComposer, + $removeJoinBuilderFromRootComposer}) => + $$UserTableAnnotationComposer( + $db: $db, + $table: $db.user, + $addJoinBuilderToRootComposer: $addJoinBuilderToRootComposer, + joinBuilder: joinBuilder, + $removeJoinBuilderFromRootComposer: + $removeJoinBuilderFromRootComposer, + )); + return composer; + } } class $$CourseTableTableManager extends RootTableManager< @@ -3315,9 +3459,9 @@ class $$CourseTableTableManager extends RootTableManager< $$CourseTableAnnotationComposer, $$CourseTableCreateCompanionBuilder, $$CourseTableUpdateCompanionBuilder, - (CourseData, BaseReferences<_$AppDatabase, $CourseTable, CourseData>), + (CourseData, $$CourseTableReferences), CourseData, - PrefetchHooks Function()> { + PrefetchHooks Function({bool user})> { $$CourseTableTableManager(_$AppDatabase db, $CourseTable table) : super(TableManagerState( db: db, @@ -3329,8 +3473,8 @@ class $$CourseTableTableManager extends RootTableManager< createComputedFieldComposer: () => $$CourseTableAnnotationComposer($db: db, $table: table), updateCompanionCallback: ({ - Value id = const Value.absent(), Value unit = const Value.absent(), + Value user = const Value.absent(), Value section = const Value.absent(), Value weekDay = const Value.absent(), Value campus = const Value.absent(), @@ -3342,8 +3486,8 @@ class $$CourseTableTableManager extends RootTableManager< Value rowid = const Value.absent(), }) => CourseCompanion( - id: id, unit: unit, + user: user, section: section, weekDay: weekDay, campus: campus, @@ -3355,8 +3499,8 @@ class $$CourseTableTableManager extends RootTableManager< rowid: rowid, ), createCompanionCallback: ({ - Value id = const Value.absent(), required String unit, + Value user = const Value.absent(), required String section, required String weekDay, required String campus, @@ -3368,8 +3512,8 @@ class $$CourseTableTableManager extends RootTableManager< Value rowid = const Value.absent(), }) => CourseCompanion.insert( - id: id, unit: unit, + user: user, section: section, weekDay: weekDay, campus: campus, @@ -3381,9 +3525,42 @@ class $$CourseTableTableManager extends RootTableManager< rowid: rowid, ), withReferenceMapper: (p0) => p0 - .map((e) => (e.readTable(table), BaseReferences(db, table, e))) + .map((e) => + (e.readTable(table), $$CourseTableReferences(db, table, e))) .toList(), - prefetchHooksCallback: null, + prefetchHooksCallback: ({user = false}) { + return PrefetchHooks( + db: db, + explicitlyWatchedTables: [], + addJoins: < + T extends TableManagerState< + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic, + dynamic>>(state) { + if (user) { + state = state.withJoin( + currentTable: table, + currentColumn: table.user, + referencedTable: $$CourseTableReferences._userTable(db), + referencedColumn: $$CourseTableReferences._userTable(db).id, + ) as T; + } + + return state; + }, + getPrefetchedDataCallback: (items) async { + return []; + }, + ); + }, )); } @@ -3396,9 +3573,9 @@ typedef $$CourseTableProcessedTableManager = ProcessedTableManager< $$CourseTableAnnotationComposer, $$CourseTableCreateCompanionBuilder, $$CourseTableUpdateCompanionBuilder, - (CourseData, BaseReferences<_$AppDatabase, $CourseTable, CourseData>), + (CourseData, $$CourseTableReferences), CourseData, - PrefetchHooks Function()>; + PrefetchHooks Function({bool user})>; class $AppDatabaseManager { final _$AppDatabase _db; diff --git a/lib/features/auth/repository/user_repository.dart b/lib/features/auth/repository/user_repository.dart index 4598a17..d974027 100644 --- a/lib/features/auth/repository/user_repository.dart +++ b/lib/features/auth/repository/user_repository.dart @@ -48,15 +48,15 @@ final class UserRepository { // Register a magnet singleton instance // TODO: (erick) enable auth with magnet - // GetIt.instance.registerSingletonIfAbsent( - // () => Magnet(credentials.admno, credentials.password), - // instanceName: "magnet", - // ); + GetIt.instance.registerSingletonIfAbsent( + () => Magnet(credentials.admno, credentials.password), + instanceName: "magnet", + ); // authenticate with magnet - const magnetResult = - // await (GetIt.instance.get(instanceName: "magnet").login()); - Right(Object()); + final magnetResult = + await (GetIt.instance.get(instanceName: "magnet").login()); + // Right(Object()); return magnetResult.fold((error) { return left(error.toString()); }, (session) async { diff --git a/lib/features/courses/cubit/course_cubit.dart b/lib/features/courses/cubit/course_cubit.dart index 9d0c84e..5b83ed2 100644 --- a/lib/features/courses/cubit/course_cubit.dart +++ b/lib/features/courses/cubit/course_cubit.dart @@ -1,3 +1,4 @@ +import 'package:academia/database/database.dart'; import 'package:academia/features/courses/cubit/course_state.dart'; import 'package:academia/features/courses/repository/course_repository.dart'; import 'package:dartz/dartz.dart'; @@ -5,20 +6,20 @@ import 'package:flutter_bloc/flutter_bloc.dart'; class CourseCubit extends Cubit { final CourseRepository _courseRepository = CourseRepository(); - CourseCubit() : super(CourseStateInitial()) { - fetchCachedCourses().then((value) {}); - } + CourseCubit() : super(CourseStateInitial()); - Future syncCourses() async { - final res = await _courseRepository.syncCoursesWithMagnet(); + Future syncCourses(UserData user) async { + emit(CourseStateLoading()); + final res = await _courseRepository.syncCoursesWithMagnet(user); if (res.isLeft()) { emit(CourseStateError(error: (res as Left).value)); } emit(CourseStateLoaded(courses: (res as Right).value)); } - Future fetchCachedCourses() async { - final result = await _courseRepository.fetchAllCachedCourses(); + Future fetchCachedCourses(UserData user) async { + emit(CourseStateLoading()); + final result = await _courseRepository.fetchAllCachedCourses(user); result.fold((error) { emit(CourseStateError(error: error)); }, (courses) { diff --git a/lib/features/courses/models/course.dart b/lib/features/courses/models/course.dart index 2884d2e..91d9ac3 100644 --- a/lib/features/courses/models/course.dart +++ b/lib/features/courses/models/course.dart @@ -1,8 +1,9 @@ +import 'package:academia/features/auth/models/user.dart'; import 'package:drift/drift.dart'; class Course extends Table { - TextColumn get id => text().nullable()(); TextColumn get unit => text()(); + TextColumn get user => text().references(User, #id).nullable()(); TextColumn get section => text()(); @JsonKey("day_of_the_week") TextColumn get weekDay => text()(); @@ -16,5 +17,5 @@ class Course extends Table { dateTime().nullable().withDefault(Constant(DateTime.now()))(); @override - Set>? get primaryKey => {id}; + Set>? get primaryKey => {unit}; } diff --git a/lib/features/courses/repository/course_local_repository.dart b/lib/features/courses/repository/course_local_repository.dart index 8d774d7..7cd596a 100644 --- a/lib/features/courses/repository/course_local_repository.dart +++ b/lib/features/courses/repository/course_local_repository.dart @@ -13,7 +13,8 @@ final class CourseLocalRepository { /// Fetches all cached courses /// Incase of an error a message of type [String] is returned /// On success, a [List] of [CourseData] is returned - Future>> fetchAllCachedCourses() async { + Future>> fetchAllCachedCourses( + UserData user) async { try { final users = await (_localDb.course.select() ..orderBy([ @@ -23,6 +24,7 @@ final class CourseLocalRepository { ), ])) .get(); + users.removeWhere((course) => course.user == user.id); return right(users); } catch (e) { return left("Failed to retrieve users with message ${e.toString()}"); diff --git a/lib/features/courses/repository/course_repository.dart b/lib/features/courses/repository/course_repository.dart index 38da255..f1eb9a1 100644 --- a/lib/features/courses/repository/course_repository.dart +++ b/lib/features/courses/repository/course_repository.dart @@ -1,5 +1,6 @@ import 'package:academia/database/database.dart'; import 'package:dartz/dartz.dart'; +import 'package:drift/drift.dart'; import 'course_local_repository.dart'; import 'course_remote_repository.dart'; @@ -12,11 +13,13 @@ final class CourseRepository { /// Fetches all cached courses /// Incase of an error a message of type [String] is returned /// On success, a [List] of [CourseData] is returned - Future>> fetchAllCachedCourses() async { - return await _localRepository.fetchAllCachedCourses(); + Future>> fetchAllCachedCourses( + UserData user) async { + return await _localRepository.fetchAllCachedCourses(user); } - Future>> syncCoursesWithMagnet() async { + Future>> syncCoursesWithMagnet( + UserData user) async { final result = await _courseRemoteRepository.fetchCoursesFromMagnet(); return result.fold((error) { @@ -24,7 +27,9 @@ final class CourseRepository { }, (courses) async { // Cache them to local db for (final course in courses) { - final res = await _localRepository.addCourseToCache(course); + final res = await _localRepository.addCourseToCache( + course.copyWith(user: Value(user.id)), + ); if (res.isLeft()) { return left((res as Left).value); } diff --git a/lib/features/courses/views/courses_page_mobile.dart b/lib/features/courses/views/courses_page_mobile.dart index b0b6781..e9f8ebd 100644 --- a/lib/features/courses/views/courses_page_mobile.dart +++ b/lib/features/courses/views/courses_page_mobile.dart @@ -13,9 +13,13 @@ class CoursesPageMobile extends StatefulWidget { class _CoursesPageMobileState extends State { late CourseCubit courseCubit = BlocProvider.of(context); + late AuthCubit authCubit = BlocProvider.of(context); @override void initState() { + courseCubit.fetchCachedCourses( + (authCubit.state as AuthenticatedState).user, + ); super.initState(); } @@ -24,7 +28,9 @@ class _CoursesPageMobileState extends State { return Scaffold( body: RefreshIndicator( onRefresh: () async { - await courseCubit.syncCourses(); + await courseCubit.syncCourses( + (authCubit.state as AuthenticatedState).user, + ); }, child: CustomScrollView( slivers: [