Skip to content
Merged
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
29 changes: 0 additions & 29 deletions lib/src/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import 'package:lichess_mobile/src/model/settings/board_preferences.dart';
import 'package:lichess_mobile/src/model/settings/general_preferences.dart';
import 'package:lichess_mobile/src/navigation.dart';
import 'package:lichess_mobile/src/network/connectivity.dart';
import 'package:lichess_mobile/src/network/http.dart';
import 'package:lichess_mobile/src/network/socket.dart';
import 'package:lichess_mobile/src/theme.dart';
import 'package:lichess_mobile/src/utils/navigation.dart';
Expand Down Expand Up @@ -62,30 +61,8 @@ class _AppState extends ConsumerState<Application> {
/// Whether the app has checked for online status for the first time.
bool _firstTimeOnlineCheck = false;

AppLifecycleListener? _appLifecycleListener;

DateTime? _pausedAt;

@override
void initState() {
_appLifecycleListener = AppLifecycleListener(
onPause: () {
_pausedAt = DateTime.now();
},
onRestart: () async {
// Invalidate ongoing games if the app was paused for more than 10 minutes.
// In theory we shouldn't need to do this, because correspondence games are updated by
// fcm messages, but in practice it's not always reliable.
// See also: [CorrespondenceService].
final online = await isOnline(ref.read(defaultClientProvider));
if (online &&
_pausedAt != null &&
DateTime.now().difference(_pausedAt!) >= const Duration(minutes: 10)) {
ref.invalidate(ongoingGamesProvider);
}
},
);

// Start services
ref.read(notificationServiceProvider).start();
ref.read(challengeServiceProvider).start();
Expand Down Expand Up @@ -124,12 +101,6 @@ class _AppState extends ConsumerState<Application> {
super.initState();
}

@override
void dispose() {
_appLifecycleListener?.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
final generalPrefs = ref.watch(generalPreferencesProvider);
Expand Down
2 changes: 1 addition & 1 deletion lib/src/db/database.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const kLichessDatabaseName = 'lichess_mobile.db';
const puzzleTTL = Duration(days: 60);
const corresGameTTL = Duration(days: 60);
const gameTTL = Duration(days: 90);
const chatReadMessagesTTL = Duration(days: 60);
const chatReadMessagesTTL = Duration(days: 180);
const httpLogTTL = Duration(days: 7);

const kStorageAnonId = '**anonymous**';
Expand Down
94 changes: 94 additions & 0 deletions lib/src/model/chat/chat.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import 'package:deep_pick/deep_pick.dart';
import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/user/user.dart';

part 'chat.freezed.dart';

typedef ChatData = ({IList<ChatMessage> lines, bool writeable});

ChatData chatDataFromPick(RequiredPick pick) {
return (
lines: pick('lines').asListOrThrow((it) => ChatMessage.fromPick(it)).toIList(),
writeable: pick('writeable').asBoolOrTrue(),
);
}

@freezed
class ChatMessage with _$ChatMessage {
const ChatMessage._();

const factory ChatMessage({
required String message,
required String? username,
required bool troll,
required bool deleted,
required bool patron,
String? flair,
String? title,
}) = _ChatMessage;

LightUser? get user =>
username != null
? LightUser(
id: UserId.fromUserName(username!),
name: username!,
title: title,
flair: flair,
isPatron: patron,
)
: null;

factory ChatMessage.fromJson(Map<String, dynamic> json) =>
ChatMessage.fromPick(pick(json).required());

factory ChatMessage.fromPick(RequiredPick pick) {
return ChatMessage(
message: pick('t').asStringOrThrow(),
username: pick('u').asStringOrNull(),
troll: pick('r').asBoolOrNull() ?? false,
deleted: pick('d').asBoolOrNull() ?? false,
patron: pick('p').asBoolOrNull() ?? false,
flair: pick('f').asStringOrNull(),
title: pick('title').asStringOrNull(),
);
}

bool get isSpam => spamRegex.hasMatch(message) || followMeRegex.hasMatch(message);
}

final RegExp spamRegex = RegExp(
[
'xcamweb.com',
'(^|[^i])chess-bot',
'chess-cheat',
'coolteenbitch',
'letcafa.webcam',
'tinyurl.com/',
'wooga.info/',
'bit.ly/',
'wbt.link/',
'eb.by/',
'001.rs/',
'shr.name/',
'u.to/',
'.3-a.net',
'.ssl443.org',
'.ns02.us',
'.myftp.info',
'.flinkup.com',
'.serveusers.com',
'badoogirls.com',
'hide.su',
'wyon.de',
'sexdatingcz.club',
'qps.ru',
'tiny.cc/',
'trasderk.blogspot.com',
't.ly/',
'shorturl.at/',
].map((url) => url.replaceAll('.', '\\.').replaceAll('/', '\\/')).join('|'),
);

final followMeRegex = RegExp('follow me|join my team', caseSensitive: false);
174 changes: 174 additions & 0 deletions lib/src/model/chat/chat_controller.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import 'dart:async';
import 'dart:math' as math;

import 'package:fast_immutable_collections/fast_immutable_collections.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:lichess_mobile/src/db/database.dart';
import 'package:lichess_mobile/src/model/auth/auth_session.dart';
import 'package:lichess_mobile/src/model/chat/chat.dart';
import 'package:lichess_mobile/src/model/common/id.dart';
import 'package:lichess_mobile/src/model/common/service/sound_service.dart';
import 'package:lichess_mobile/src/model/common/socket.dart';
import 'package:lichess_mobile/src/model/game/game_controller.dart';
import 'package:lichess_mobile/src/model/tournament/tournament_controller.dart';
import 'package:lichess_mobile/src/model/user/user.dart';
import 'package:lichess_mobile/src/network/socket.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:sqflite/sqflite.dart';

part 'chat_controller.freezed.dart';
part 'chat_controller.g.dart';

const _tableName = 'chat_read_messages';
String _storeKey(StringId id) => 'chat.$id';

@immutable
sealed class ChatOptions {
const ChatOptions();

StringId get id;
LightUser? get opponent;
bool get isPublic;
bool get writeable;

@override
String toString() =>
'ChatOptions(id: $id, opponent: $opponent, isPublic: $isPublic, writeable: $writeable)';
}

@freezed
class GameChatOptions extends ChatOptions with _$GameChatOptions {
const GameChatOptions._();
const factory GameChatOptions({required GameFullId id, required LightUser? opponent}) =
_GameChatOptions;

@override
bool get isPublic => false;

@override
bool get writeable => true;
}

@freezed
class TournamentChatOptions extends ChatOptions with _$TournamentChatOptions {
const TournamentChatOptions._();
const factory TournamentChatOptions({required TournamentId id, required bool writeable}) =
_TournamentChatOptions;

@override
LightUser? get opponent => null;

@override
bool get isPublic => true;
}

/// A provider that gets the chat unread messages
@riverpod
Future<int> chatUnread(Ref ref, ChatOptions options) async {
return ref.watch(chatControllerProvider(options).selectAsync((s) => s.unreadMessages));
}

const IList<ChatMessage> _kEmptyMessages = IListConst([]);

@riverpod
class ChatController extends _$ChatController {
StreamSubscription<SocketEvent>? _subscription;

LightUser? get _me => ref.read(authSessionProvider)?.user;

@override
Future<ChatState> build(ChatOptions options) async {
_subscription?.cancel();
_subscription = socketGlobalStream.listen(_handleSocketEvent);

ref.onDispose(() {
_subscription?.cancel();
});

final initialMessages = await switch (options) {
GameChatOptions(:final id) => ref.watch(
gameControllerProvider(id).selectAsync((s) => s.game.chat?.lines),
),
TournamentChatOptions(:final id) => ref.watch(
tournamentControllerProvider(id).selectAsync((s) => s.tournament.chat?.lines),
),
};

final filteredMessages = _selectMessages(initialMessages ?? _kEmptyMessages);
final readMessagesCount = await _getReadMessagesCount();

return ChatState(
messages: filteredMessages,
unreadMessages: math.max(0, filteredMessages.length - readMessagesCount),
);
}

/// Sends a message to the chat.
void postMessage(String message) {
ref.read(socketPoolProvider).currentClient.send('talk', message);
}

/// Resets the unread messages count to 0 and saves the number of read messages.
Future<void> markMessagesAsRead() async {
if (state.hasValue) {
await _setReadMessagesCount(state.requireValue.messages.length);
}
state = state.whenData((s) => s.copyWith(unreadMessages: 0));
}

IList<ChatMessage> _selectMessages(IList<ChatMessage> all) {
return all
.where(
(m) =>
!m.deleted && (!m.troll || m.username?.toLowerCase() == _me?.id.value) && !m.isSpam,
)
.toIList();
}

Future<int> _getReadMessagesCount() async {
final db = await ref.read(databaseProvider.future);
final result = await db.query(
_tableName,
columns: ['nbRead'],
where: 'id = ?',
whereArgs: [_storeKey(options.id)],
);
return result.firstOrNull?['nbRead'] as int? ?? 0;
}

Future<void> _setReadMessagesCount(int count) async {
final db = await ref.read(databaseProvider.future);
await db.insert(_tableName, {
'id': _storeKey(options.id),
'lastModified': DateTime.now().toIso8601String(),
'nbRead': count,
}, conflictAlgorithm: ConflictAlgorithm.replace);
}

void _handleSocketEvent(SocketEvent event) {
if (!state.hasValue) return;

if (event.topic == 'message') {
final data = event.data as Map<String, dynamic>;
final message = ChatMessage.fromJson(data);
state = state.whenData((s) {
final oldMessages = s.messages;
final newMessages = _selectMessages(oldMessages.add(message));
final newUnread = newMessages.length - oldMessages.length;
if (options.isPublic == false && newUnread > 0) {
ref.read(soundServiceProvider).play(Sound.confirmation, volume: 0.5);
}
return s.copyWith(messages: newMessages, unreadMessages: s.unreadMessages + newUnread);
});
}
}
}

@freezed
class ChatState with _$ChatState {
const ChatState._();

const factory ChatState({required IList<ChatMessage> messages, required int unreadMessages}) =
_ChatState;
}
Loading