Skip to content

Commit

Permalink
Migrate models to nnbd
Browse files Browse the repository at this point in the history
  • Loading branch information
cenomla committed Apr 21, 2021
1 parent f563c74 commit 4ebf70a
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 90 deletions.
27 changes: 16 additions & 11 deletions flokk_src/lib/models/abstract_model.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
// @dart=2.9
import 'dart:convert';

import 'package:flokk/_internal/log.dart';
import 'package:flokk/_internal/universal_file/universal_file.dart';
import 'package:flutter/cupertino.dart';

abstract class AbstractModel extends ChangeNotifier {
UniversalFile _file;
UniversalFile? _file;

void reset([bool notify = true]) {
copyFromJson({});
Expand All @@ -30,13 +29,17 @@ abstract class AbstractModel extends ChangeNotifier {

//Loads a string from disk, and parses it into ourselves.
Future<void> load() async {
String string = await _file.read().catchError((e, s) => Log.e(e, stack: s)) ?? "{}";
if (string != null) {
copyFromJson(jsonDecode(string));
}
final file = _file;
if (file == null) return;

String string = await file.read().catchError((e, s) {
Log.e(e, stack: s);
return "{}";
});
copyFromJson(jsonDecode(string));
}

Future<void> save() async => _file.write(jsonEncode(toJson()));
Future<void> save() async => _file?.write(jsonEncode(toJson()));

//Enable file serialization, remember to override the to/from serialization methods as well
void enableSerialization(String fileName) {
Expand All @@ -53,10 +56,12 @@ abstract class AbstractModel extends ChangeNotifier {
throw UnimplementedError();
}

List<T> toList<T>(dynamic json, Function(dynamic) fromJson) {
final List<T> list = (json as Iterable)?.map((e) {
return e == null ? null : fromJson(e) as T;
})?.toList();
List<T> toList<T>(dynamic json, dynamic Function(dynamic) fromJson) {
final List<T> list = (json as Iterable?)?.map((e) {
return e == null ? e : fromJson(e) as T?;
}).where((e) => e != null).whereType<T>().toList() ?? [];

return list;
}
}

15 changes: 7 additions & 8 deletions flokk_src/lib/models/app_model.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @dart=2.9
import 'package:flokk/data/contact_data.dart';
import 'package:flokk/models/abstract_model.dart';
import 'package:flokk/models/contacts_model.dart';
Expand Down Expand Up @@ -63,15 +62,15 @@ class AppModel extends AbstractModel {
/// /////////////////////////////////////////////////
/// Current dashboard sections (serialized)
DashboardContactsSectionType get dashContactsSection => _dashContactsSection;
DashboardContactsSectionType _dashContactsSection;
DashboardContactsSectionType _dashContactsSection = DashboardContactsSectionType.Favorites;

set dashContactsSection(DashboardContactsSectionType value) {
_dashContactsSection = value;
notifyListeners();
}

DashboardSocialSectionType get dashSocialSection => _dashSocialSection;
DashboardSocialSectionType _dashSocialSection;
DashboardSocialSectionType _dashSocialSection = DashboardSocialSectionType.All;

set dashSocialSection(DashboardSocialSectionType value) {
_dashSocialSection = value;
Expand All @@ -80,10 +79,10 @@ class AppModel extends AbstractModel {

/// //////////////////////////////////////////////////
/// Selected edit target, controls visibility of the edit panel and selected rows in the various views
ContactData get selectedContact => _selectedContact;
ContactData _selectedContact;
ContactData get selectedContact => _selectedContact ?? ContactData();
ContactData? _selectedContact;

void touchSelectedSocial() => contactsModel.touchSocialById(selectedContact?.id);
void touchSelectedSocial() => contactsModel.touchSocialById(selectedContact.id);

/// Current selected edit target, controls visibility of the edit panel
set selectedContact(ContactData value) {
Expand All @@ -109,7 +108,7 @@ class AppModel extends AbstractModel {
/// //////////////////////////////////////////////////
/// Holds current page type, synchronizes leftMenu with the mainContent
PageType get currentMainPage => _currentMainPage;
PageType _currentMainPage;
PageType _currentMainPage = PageType.None;

set currentMainPage(PageType value) {
_currentMainPage = value;
Expand All @@ -129,7 +128,7 @@ class AppModel extends AbstractModel {
/// //////////////////////////////////////////
/// Current Theme (serialized)
ThemeType get theme => _theme;
ThemeType _theme;
ThemeType _theme = ThemeType.FlockGreen;

set theme(ThemeType value) {
_theme = value;
Expand Down
21 changes: 9 additions & 12 deletions flokk_src/lib/models/auth_model.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
// @dart=2.9
import 'package:flokk/_internal/log.dart';
import "package:flokk/_internal/utils/string_utils.dart";
import "package:flokk/models/abstract_model.dart";
import 'package:google_sign_in/google_sign_in.dart';

class AuthModel extends AbstractModel {
String googleRefreshToken;
String googleEmail;
String googleSyncToken;
DateTime _expiry = DateTime.fromMillisecondsSinceEpoch(0);
GoogleSignIn googleSignIn; //instance of google sign in; only set if web
String? googleRefreshToken;
String? googleEmail;
String? googleSyncToken;
DateTime _expiry = DateTime.utc(2099);
GoogleSignIn? googleSignIn; //instance of google sign in; only set if web

AuthModel() {
enableSerialization("auth.dat");
Expand All @@ -33,9 +32,9 @@ class AuthModel extends AbstractModel {

/////////////////////////////////////////////////////////////////////
// Access Token
String _googleAccessToken;
String? _googleAccessToken;

String get googleAccessToken => _googleAccessToken;
String get googleAccessToken => _googleAccessToken ?? "";

set googleAccessToken(String value) {
_googleAccessToken = value;
Expand All @@ -49,10 +48,8 @@ class AuthModel extends AbstractModel {
googleRefreshToken = null;
googleSyncToken = null;
googleEmail = null;
_expiry = null;
if (googleSignIn != null) {
googleSignIn.disconnect();
}
_expiry = DateTime.utc(2099);
googleSignIn?.disconnect();
super.reset(notify);
}

Expand Down
63 changes: 32 additions & 31 deletions flokk_src/lib/models/contacts_model.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @dart=2.9
import 'package:flokk/_internal/log.dart';
import 'package:flokk/_internal/utils/string_utils.dart';
import 'package:flokk/data/contact_data.dart';
Expand All @@ -17,14 +16,15 @@ class ContactsModel extends AbstractModel {
final tweetsCooldown = Duration(minutes: 1);
final contactGroupsCooldown = Duration(seconds: 20);

DateTime lastUpdatedGroups = DateTime.fromMillisecondsSinceEpoch(0); //can't just use epoch because "only static members can be used in initializers"
DateTime lastUpdatedGroups = DateTime.fromMillisecondsSinceEpoch(
0); //can't just use epoch because "only static members can be used in initializers"

ContactsModel() {
enableSerialization("contacts.dat");
}

TwitterModel twitterModel;
GithubModel gitModel;
late TwitterModel twitterModel;
late GithubModel gitModel;

//Groups
List<GroupData> get allGroups => _allGroups ?? [];
Expand All @@ -36,9 +36,9 @@ class ContactsModel extends AbstractModel {
notifyListeners();
}

GroupData getGroupById(String value) => _allGroups.firstWhere((g) => g.id == value, orElse: () => null);
GroupData getGroupById(String value) => _allGroups.firstWhere((g) => g.id == value, orElse: () => GroupData());

GroupData getGroupByName(String value) => _allGroups.firstWhere((g) => g.name == value, orElse: () => null);
GroupData getGroupByName(String value) => _allGroups.firstWhere((g) => g.name == value, orElse: () => GroupData());

//Contacts List
List<ContactData> get activeContacts => allContacts.where((c) => !c.isDeleted).toList();
Expand All @@ -54,7 +54,7 @@ class ContactsModel extends AbstractModel {
notifyListeners();
}

ContactData getContactById(String id) => _allContacts.firstWhere((c) => c.id == id, orElse: () => null);
ContactData getContactById(String id) => _allContacts.firstWhere((c) => c.id == id, orElse: () => ContactData());

void addContact(ContactData contact) {
_allContacts.add(contact);
Expand All @@ -70,7 +70,7 @@ class ContactsModel extends AbstractModel {

void swapContactById(ContactData newContact) {
ContactData oldContact = getContactById(newContact.id);
if (oldContact != null) {
if (oldContact != ContactData()) {
//[SB] Keep isStarred in sync when we swap contents since this is injected by the [updateContactsWithGroupData] fxn.
newContact.isStarred = oldContact.isStarred;
newContact.groupList = oldContact.groupList;
Expand Down Expand Up @@ -98,7 +98,7 @@ class ContactsModel extends AbstractModel {

void touchSocialById(String id) {
SocialContactData social = getSocialById(id);
if (social != null) {
if (social != SocialContactData()) {
social.lastCheckedTweets = DateTime.now();
social.lastCheckedGit = DateTime.now();
notifyListeners();
Expand All @@ -107,17 +107,17 @@ class ContactsModel extends AbstractModel {
}

void clearGitCooldown(ContactData contact) {
getSocialById(contact.id)?.lastUpdatedGit = epoch;
getSocialById(contact.id)?.lastCheckedGit = epoch;
getSocialById(contact.id).lastUpdatedGit = epoch;
getSocialById(contact.id).lastCheckedGit = epoch;
}

void clearTwitterCooldown(ContactData contact) {
getSocialById(contact.id)?.lastUpdatedTwitter = epoch;
getSocialById(contact.id)?.lastCheckedTweets = epoch;
getSocialById(contact.id).lastUpdatedTwitter = epoch;
getSocialById(contact.id).lastCheckedTweets = epoch;
}

bool canRefreshGitEventsFor(String gitUsername) {
DateTime lastUpdate = getSocialContactByGit(gitUsername)?.lastUpdatedGit ?? epoch;
DateTime lastUpdate = getSocialContactByGit(gitUsername).lastUpdatedGit ?? epoch;
return DateTime.now().difference(lastUpdate) > gitEventsCooldown;
}

Expand All @@ -129,33 +129,34 @@ class ContactsModel extends AbstractModel {
bool get canRefreshContactGroups => DateTime.now().difference(lastUpdatedGroups ?? epoch) > contactGroupsCooldown;

//Updates the timestamps when social feeds are refreshed for contact
void updateSocialTimestamps({String twitterHandle, String gitUsername}) {
if (!StringUtils.isEmpty(twitterHandle)) {
getSocialContactByTwitter(twitterHandle)?.lastUpdatedTwitter = DateTime.now();
void updateSocialTimestamps({String twitterHandle = "", String gitUsername = ""}) {
if (twitterHandle.isNotEmpty) {
getSocialContactByTwitter(twitterHandle).lastUpdatedTwitter = DateTime.now();
}
if (!StringUtils.isEmpty(gitUsername)) {
getSocialContactByGit(gitUsername)?.lastUpdatedGit = DateTime.now();
if (gitUsername.isNotEmpty) {
getSocialContactByGit(gitUsername).lastUpdatedGit = DateTime.now();
}
}

void updateContactDataGithubValidity(String gitUsername, bool isValid) {
allContacts?.firstWhere((x) => x.gitUsername == gitUsername, orElse: () => null)?.hasValidGit = isValid;
allContacts.firstWhere((x) => x.gitUsername == gitUsername, orElse: () => ContactData()).hasValidGit = isValid;
}

void updateContactDataTwitterValidity(String twitterHandle, bool isValid) {
allContacts?.firstWhere((x) => x.twitterHandle == twitterHandle, orElse: () => null)?.hasValidTwitter = isValid;
allContacts.firstWhere((x) => x.twitterHandle == twitterHandle, orElse: () => ContactData()).hasValidTwitter =
isValid;
}

ContactData getContactByGit(String gitUsername) =>
allContacts?.firstWhere((x) => x.gitUsername == gitUsername, orElse: () => null);
allContacts.firstWhere((x) => x.gitUsername == gitUsername, orElse: () => ContactData());

ContactData getContactByTwitter(String twitterHandle) =>
allContacts?.firstWhere((x) => x.twitterHandle == twitterHandle, orElse: () => null);
allContacts.firstWhere((x) => x.twitterHandle == twitterHandle, orElse: () => ContactData());

SocialContactData getSocialContactByGit(String gitUsername) => getSocialById(getContactByGit(gitUsername)?.id);
SocialContactData getSocialContactByGit(String gitUsername) => getSocialById(getContactByGit(gitUsername).id);

SocialContactData getSocialContactByTwitter(String twitterHandle) =>
getSocialById(getContactByTwitter(twitterHandle)?.id);
getSocialById(getContactByTwitter(twitterHandle).id);

//Get a list of contacts with the most activity (based on their calculated "points" for each social activity)
List<SocialContactData> get mostActiveSocialContacts =>
Expand All @@ -166,8 +167,8 @@ class ContactsModel extends AbstractModel {
..sort((a, b) => (b.latestActivity?.createdAt ?? epoch).compareTo(a.latestActivity?.createdAt ?? epoch));

SocialContactData getSocialById(String id) {
if (StringUtils.isEmpty(id)) return null;
return allSocialContacts?.firstWhere((c) => c.contactId == id, orElse: () => null);
if (id.isEmpty) return SocialContactData();
return allSocialContacts.firstWhere((c) => c.contactId == id, orElse: () => SocialContactData());
}

//Get a list of contacts with upcoming dates (repeated contacts are expected if they have multiple events that are upcoming)
Expand Down Expand Up @@ -201,7 +202,7 @@ class ContactsModel extends AbstractModel {
if (g.groupType == GroupType.UserContactGroup) {
for (String id in g.members) {
ContactData contact = getContactById(id);
if (contact != null) {
if (contact != ContactData()) {
contact.groupList.add(g);
// print("name: ${contact.nameFull} labels: ${contact.groupList.join(',')}");
}
Expand Down Expand Up @@ -252,9 +253,9 @@ class ContactsModel extends AbstractModel {
//Json Serialization
@override
ContactsModel copyFromJson(Map<String, dynamic> value) {
_allContacts = toList(value['_allContacts'], (j) => ContactData.fromJson(j)) ?? [];
_allGroups = toList(value['_allGroups'], (j) => GroupData.fromJson(j)) ?? [];
_allSocialContacts = toList(value['_allSocialContacts'], (j) => SocialContactData.fromJson(j)) ?? [];
_allContacts = toList(value['_allContacts'], (j) => ContactData.fromJson(j));
_allGroups = toList(value['_allGroups'], (j) => GroupData.fromJson(j));
_allSocialContacts = toList(value['_allSocialContacts'], (j) => SocialContactData.fromJson(j));
_updateSocialContacts();
return this;
}
Expand Down
Loading

0 comments on commit 4ebf70a

Please sign in to comment.