Now we have list of tracked players

(just like side bar in main view)
This commit is contained in:
dan63047 2023-06-10 00:04:51 +03:00
parent ae14e1789c
commit a3b056953a
6 changed files with 140 additions and 63 deletions

View File

@ -3,7 +3,7 @@ import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:tetra_stats/views/main_view.dart'; import 'package:tetra_stats/views/main_view.dart';
import 'package:tetra_stats/views/compare_view.dart'; import 'package:tetra_stats/views/compare_view.dart';
import 'package:tetra_stats/views/settings_view.dart'; import 'package:tetra_stats/views/settings_view.dart';
import 'package:tetra_stats/views/states_view.dart'; import 'package:tetra_stats/views/tracked_players_view.dart';
import 'package:tetra_stats/views/calc_view.dart'; import 'package:tetra_stats/views/calc_view.dart';
void main() { void main() {

View File

@ -19,6 +19,7 @@ class DB {
final db = await openDatabase(dbPath); final db = await openDatabase(dbPath);
_db = db; _db = db;
await db.execute(createTetrioUsersTable); await db.execute(createTetrioUsersTable);
await db.execute(createTetrioUsersToTrack);
} on MissingPlatformDirectoryException { } on MissingPlatformDirectoryException {
throw UnableToGetDocuments(); throw UnableToGetDocuments();
} }

View File

@ -2,17 +2,13 @@ import 'dart:async';
import 'dart:convert'; import 'dart:convert';
import 'dart:developer' as developer; import 'dart:developer' as developer;
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:sqflite/sqflite.dart';
// import 'package:sqflite/sqflite.dart';
// import 'package:path_provider/path_provider.dart' show MissingPlatformDirectoryException, getApplicationDocumentsDirectory;
// import 'package:path/path.dart' show join;
import 'package:tetra_stats/services/crud_exceptions.dart'; import 'package:tetra_stats/services/crud_exceptions.dart';
import 'package:tetra_stats/services/sqlite_db_controller.dart'; import 'package:tetra_stats/services/sqlite_db_controller.dart';
import 'package:tetra_stats/data_objects/tetrio.dart'; import 'package:tetra_stats/data_objects/tetrio.dart';
const String dbName = "TetraStats.db"; const String dbName = "TetraStats.db";
const String tetrioUsersTable = "tetrioUsers"; const String tetrioUsersTable = "tetrioUsers";
const String tetrioUsersToTrackTable = "tetrioUsersToTrack";
const String idCol = "id"; const String idCol = "id";
const String nickCol = "nickname"; const String nickCol = "nickname";
const String statesCol = "jsonStates"; const String statesCol = "jsonStates";
@ -23,6 +19,12 @@ const String createTetrioUsersTable = '''
"jsonStates" TEXT, "jsonStates" TEXT,
PRIMARY KEY("id") PRIMARY KEY("id")
);'''; );''';
const String createTetrioUsersToTrack = '''
CREATE TABLE IF NOT EXISTS "tetrioUsersToTrack" (
"id" TEXT NOT NULL UNIQUE,
PRIMARY KEY("ID")
)
''';
class TetrioService extends DB { class TetrioService extends DB {
Map<String, List<TetrioPlayer>> _players = {}; Map<String, List<TetrioPlayer>> _players = {};
@ -50,9 +52,9 @@ class TetrioService extends DB {
developer.log("_cachePlayers: $_players", name: "services/tetrio_crud"); developer.log("_cachePlayers: $_players", name: "services/tetrio_crud");
} }
Future<void> deletePlayer({required String id, required DB udb}) async { Future<void> deletePlayer(String id) async {
await ensureDbIsOpen(); await ensureDbIsOpen();
final db = udb.getDatabaseOrThrow(); final db = getDatabaseOrThrow();
final deletedPlayer = await db.delete(tetrioUsersTable, where: '$idCol = ?', whereArgs: [id.toLowerCase()]); final deletedPlayer = await db.delete(tetrioUsersTable, where: '$idCol = ?', whereArgs: [id.toLowerCase()]);
if (deletedPlayer != 1) { if (deletedPlayer != 1) {
throw CouldNotDeletePlayer(); throw CouldNotDeletePlayer();
@ -62,16 +64,6 @@ class TetrioService extends DB {
} }
} }
// Future <List<TetrioPlayer>> getOrCreatePlayer({required String id}) async {
// try{
// final player = await getPlayer(id: id);
// return player;
// } on TetrioPlayerNotExist{
// final player = await createPlayer(tetrioPlayer: tetrioPlayer)
// }
// }
Future<void> createPlayer(TetrioPlayer tetrioPlayer) async { Future<void> createPlayer(TetrioPlayer tetrioPlayer) async {
ensureDbIsOpen(); ensureDbIsOpen();
final db = getDatabaseOrThrow(); final db = getDatabaseOrThrow();
@ -87,6 +79,36 @@ class TetrioService extends DB {
_tetrioStreamController.add(_players); _tetrioStreamController.add(_players);
} }
Future<void> addPlayerToTrack(TetrioPlayer tetrioPlayer) async {
ensureDbIsOpen();
final db = getDatabaseOrThrow();
final results = await db.query(tetrioUsersToTrackTable, where: '$idCol = ?', whereArgs: [tetrioPlayer.userId.toLowerCase()]);
if (results.isNotEmpty) {
throw TetrioPlayerAlreadyExist();
}
db.insert(tetrioUsersToTrackTable, {idCol: tetrioPlayer.userId});
}
Future<Iterable<String>> getAllPlayerToTrack() async {
await ensureDbIsOpen();
final db = getDatabaseOrThrow();
final players = await db.query(tetrioUsersToTrackTable);
developer.log("getAllPlayerToTrack: $players", name: "services/tetrio_crud");
return players.map((noteRow) => noteRow["id"].toString());
}
Future<void> deletePlayerToTrack(String id) async {
await ensureDbIsOpen();
final db = getDatabaseOrThrow();
final deletedPlayer = await db.delete(tetrioUsersToTrackTable, where: '$idCol = ?', whereArgs: [id.toLowerCase()]);
if (deletedPlayer != 1) {
throw CouldNotDeletePlayer();
} else {
// _players.removeWhere((key, value) => key == id);
// _tetrioStreamController.add(_players);
}
}
Future<void> storeState(TetrioPlayer tetrioPlayer) async { Future<void> storeState(TetrioPlayer tetrioPlayer) async {
ensureDbIsOpen(); ensureDbIsOpen();
final db = getDatabaseOrThrow(); final db = getDatabaseOrThrow();

View File

@ -156,7 +156,7 @@ class _MainState extends State<MainView> with SingleTickerProviderStateMixin {
), ),
const PopupMenuItem( const PopupMenuItem(
value: "/states", value: "/states",
child: Text('States'), child: Text('Players you track'),
), ),
const PopupMenuItem( const PopupMenuItem(
value: "/calc", value: "/calc",
@ -376,7 +376,7 @@ class _UserThingy extends StatelessWidget {
return LayoutBuilder(builder: (context, constraints) { return LayoutBuilder(builder: (context, constraints) {
bool bigScreen = constraints.maxWidth > 768; bool bigScreen = constraints.maxWidth > 768;
double bannerHeight = bigScreen ? 240 : 120; double bannerHeight = bigScreen ? 240 : 120;
double pfpHeight = bigScreen ? 64 : 32; double pfpHeight = 128;
return Column( return Column(
children: [ children: [
Flex( Flex(
@ -407,7 +407,7 @@ class _UserThingy extends StatelessWidget {
? Image.asset( ? Image.asset(
"res/avatars/tetrio_banned.png", "res/avatars/tetrio_banned.png",
fit: BoxFit.fitHeight, fit: BoxFit.fitHeight,
height: 128, height: pfpHeight,
) )
: player.avatarRevision != null : player.avatarRevision != null
? Image.network("https://tetr.io/user-content/avatars/${player.userId}.jpg?rv=${player.avatarRevision}", ? Image.network("https://tetr.io/user-content/avatars/${player.userId}.jpg?rv=${player.avatarRevision}",
@ -416,31 +416,47 @@ class _UserThingy extends StatelessWidget {
return Image.asset( return Image.asset(
"res/avatars/tetrio_anon.png", "res/avatars/tetrio_anon.png",
fit: BoxFit.fitHeight, fit: BoxFit.fitHeight,
height: 128, height: pfpHeight,
); );
}) })
: Image.asset( : Image.asset(
"res/avatars/tetrio_anon.png", "res/avatars/tetrio_anon.png",
fit: BoxFit.fitHeight, fit: BoxFit.fitHeight,
height: 128, height: pfpHeight,
), ),
), ),
), ),
if (player.verified)
Padding(
padding: EdgeInsets.fromLTRB(
pfpHeight - 22,
bigScreen // verified icon top padding:
? (player.bannerRevision != null ? bannerHeight + pfpHeight - 96 : pfpHeight + pfpHeight - 32) // for big screen
: (player.bannerRevision != null ? bannerHeight + pfpHeight - 58 : pfpHeight + pfpHeight - 32), // for small screen
0,
0),
child: const Icon(Icons.verified),
)
], ],
), ),
Flexible( Flexible(
child: Column( child: Column(
children: [ children: [
Text(player.username, style: TextStyle(fontFamily: "Eurostile Round Extended", fontSize: bigScreen ? 42 : 28)), Text(player.username, style: TextStyle(fontFamily: "Eurostile Round Extended", fontSize: bigScreen ? 42 : 28)),
TextButton( TextButton(
child: Text(player.userId, style: const TextStyle(fontFamily: "Eurostile Round Condensed", fontSize: 14)), child: Text(player.userId, style: const TextStyle(fontFamily: "Eurostile Round Condensed", fontSize: 14)),
onPressed: () { onPressed: () {
copyToClipboard(player.userId); copyToClipboard(player.userId);
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Copied to clipboard!"))); ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Copied to clipboard!")));
}), }),
], IconButton(
), icon: Icon(Icons.addchart),
), style: ButtonStyle(),
onPressed: () {},
),
Text("Track")
],
)),
], ],
), ),
(player.role != "banned") (player.role != "banned")
@ -459,11 +475,7 @@ class _UserThingy extends StatelessWidget {
), ),
if (player.gameTime >= Duration.zero) if (player.gameTime >= Duration.zero)
_StatCellNum( _StatCellNum(
playerStat: player.gameTime.inHours, playerStat: player.gameTime.inHours, playerStatLabel: "Hours\nPlayed", isScreenBig: bigScreen, snackBar: player.gameTime.toString()),
playerStatLabel: "Hours\nPlayed",
isScreenBig: bigScreen,
snackBar: player.gameTime.toString(),
),
if (player.gamesPlayed >= 0) _StatCellNum(playerStat: player.gamesPlayed, isScreenBig: bigScreen, playerStatLabel: "Online\nGames"), if (player.gamesPlayed >= 0) _StatCellNum(playerStat: player.gamesPlayed, isScreenBig: bigScreen, playerStatLabel: "Online\nGames"),
if (player.gamesWon >= 0) _StatCellNum(playerStat: player.gamesWon, isScreenBig: bigScreen, playerStatLabel: "Games\nWon"), if (player.gamesWon >= 0) _StatCellNum(playerStat: player.gamesWon, isScreenBig: bigScreen, playerStatLabel: "Games\nWon"),
if (player.friendCount > 0) _StatCellNum(playerStat: player.friendCount, isScreenBig: bigScreen, playerStatLabel: "Friends"), if (player.friendCount > 0) _StatCellNum(playerStat: player.friendCount, isScreenBig: bigScreen, playerStatLabel: "Friends"),

View File

@ -1,23 +0,0 @@
import 'package:flutter/material.dart';
class StatesView extends StatefulWidget {
const StatesView({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => StatesState();
}
class StatesState extends State<StatesView> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("States of NICKNAME account"),
),
backgroundColor: Colors.black,
body: const SafeArea(
child: Text(
"So it's gonna be possible to store history of the account. One single piece of account history is what i call \"State\". In this view you will be able to control states, delete really old ones if too many.\n\nRight now app doesn't even store it.")),
);
}
}

View File

@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import 'package:tetra_stats/data_objects/tetrio.dart';
import 'package:tetra_stats/services/tetrio_crud.dart';
final TetrioService teto = TetrioService();
class StatesView extends StatefulWidget {
const StatesView({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => StatesState();
}
class StatesState extends State<StatesView> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Players you track"),
),
backgroundColor: Colors.black,
body: SafeArea(
child: StreamBuilder(
stream: teto.allPlayers,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Center(child: Text('none case of StreamBuilder'));
case ConnectionState.waiting:
case ConnectionState.active:
final allPlayers = (snapshot.data != null) ? snapshot.data as Map<String, List<TetrioPlayer>> : <String, List<TetrioPlayer>>{};
List<String> keys = allPlayers.keys.toList();
print(allPlayers.toString());
return NestedScrollView(
headerSliverBuilder: (context, value) {
return [
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(left: 16),
child: Text(
'There is ${allPlayers.length} players',
style: TextStyle(color: Colors.white, fontSize: 25),
),
)),
const SliverToBoxAdapter(child: Divider())
];
},
body: ListView.builder(
itemCount: allPlayers.length,
itemBuilder: (context, index) {
return ListTile(
title: Text("${allPlayers[keys[index]]?.last.username}: ${allPlayers[keys[index]]?.length} states"),
subtitle: Text("From ${allPlayers[keys[index]]?.first.state} until ${allPlayers[keys[index]]?.last.state}"),
onTap: () {},
);
}));
case ConnectionState.done:
return Center(
child: Text('done case of StreamBuilder',
style: const TextStyle(fontFamily: "Eurostile Round Extended", fontSize: 42), textAlign: TextAlign.center));
}
})),
);
}
}