Skip to content

Commit

Permalink
Merge pull request #36 from SEbbaDK/server-cache-leaderboards
Browse files Browse the repository at this point in the history
Cache leaderboards and provide leaderboard data with user
  • Loading branch information
SEbbaDK committed May 22, 2021
2 parents 034f643 + 35f789e commit 34931e4
Show file tree
Hide file tree
Showing 47 changed files with 1,572 additions and 671 deletions.
20 changes: 20 additions & 0 deletions api-server.nix
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ let
databaseSetup = ./server/database/create-role-and-database.sql;
tableSetup = pkgs.writeText "setup.sql" ''
${builtins.readFile ./server/database/create-tables.sql}
${builtins.readFile ./server/database/create-materialized-views.sql}
${mockData}
'';
in
Expand Down Expand Up @@ -63,6 +64,25 @@ in
wantedBy = [ "default.target" ];
};

systemd.services.maptogether-refresh-views = {
description = "Refresh the MapTogether views";
serviceConfig = {
Type = "oneshot";
User = "maptogether";
Group = "maptogether";
ExecStart = "${pkgs.postgresql}/bin/psql -d maptogether -f ${./server/database/refresh-materialized-views.sql}";
};
requires = [ "maptogether-database-setup.service" "postgresql.service" ];
after = [ "maptogether-database-setup.service" "postgresql.service" ];
wantedBy = [ "default.target" ];
};

systemd.timers.maptogether-refresh-views = {
description = "Timer to trigger refresh";
timerConfig.OnCalendar = "*:*:0"; # once a minute
wantedBy = [ "timers.target" ];
};

users.groups.maptogether.gid = 1005;
users.users.maptogether = {
isSystemUser = true;
Expand Down
7 changes: 3 additions & 4 deletions client/lib/location_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import 'package:latlong/latlong.dart';
import 'package:location/location.dart';

class LocationHandler extends ChangeNotifier {

// From location lib
Location _locationService = Location();

Expand All @@ -18,9 +17,9 @@ class LocationHandler extends ChangeNotifier {

LocationHandler() {
mapController = MapController();
rotationStream = mapController.mapEventStream
.map((_) => mapController.rotation)
.map((d) => (d / 360.0) * (2.0 * math.pi));
rotationStream = mapController.mapEventStream
.map((_) => mapController.rotation)
.map((d) => (d / 360.0) * (2.0 * math.pi));
initLocationService();
}

Expand Down
13 changes: 4 additions & 9 deletions client/lib/login_flow.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import 'package:client/login_handler.dart';
import 'package:client/widgets/app_bar.dart';
import 'package:client/widgets/future_loader.dart';


class LoginWebView extends StatelessWidget {
final String url;

Expand Down Expand Up @@ -52,13 +51,10 @@ class LoginWebView extends StatelessWidget {
MaterialPageRoute<bool> loginPage() => MaterialPageRoute<bool>(
builder: (context) => FutureLoader<String>(
future: context.watch<LoginHandler>().loginUrl(),
builder: (BuildContext context, String url) =>
LoginWebView(url)
)
);

builder: (BuildContext context, String url) => LoginWebView(url)));

Future<bool> requestLogin(BuildContext context, {bool social = false}) => request(
Future<bool> requestLogin(BuildContext context, {bool social = false}) =>
request(
context,
title: social
? 'You must login to access social features'
Expand All @@ -71,8 +67,7 @@ Future<bool> requestLogin(BuildContext context, {bool social = false}) => reques
).then((answer) async {
if (answer == false) return false;
final login = await Navigator.push<bool>(context, loginPage());
if (login && social)
await context.read<LoginHandler>().optIn();
if (login && social) await context.read<LoginHandler>().optIn();
return login;
});

Expand Down
52 changes: 24 additions & 28 deletions client/lib/login_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,23 @@ const _ckey = String.fromEnvironment('CKEY');
const _csec = String.fromEnvironment('CSEC');

class LoginHandler extends ChangeNotifier {

// OSM things
final _env = osm.ApiEnv.dev('master');
final osm.Auth _auth = osm.Auth(_ckey, _csec, osm.ApiEnv.dev('master'));
osm.Api _osmApi = null;
var _tempToken = null;

osm.Api osmApi() {
if (!loggedIntoOSM())
throw Exception('Cannot get OSM Api before logging in');
if (_osmApi == null)
_osmApi = osm.Api(
'MapTogether v0.1.0pre',
_auth.getClient(_auth.createCredentials(_accessToken(), _accessSecret())),
_env
);
return _osmApi;
}
osm.Api osmApi() {
if (!loggedIntoOSM())
throw Exception('Cannot get OSM Api before logging in');
if (_osmApi == null)
_osmApi = osm.Api(
'MapTogether v0.1.0pre',
_auth.getClient(
_auth.createCredentials(_accessToken(), _accessSecret())),
_env);
return _osmApi;
}

Future<String> loginUrl() async {
_tempToken = (await _auth.getTemporaryToken()).credentials;
Expand All @@ -41,22 +40,22 @@ class LoginHandler extends ChangeNotifier {
return true;
}


// MT things

mt.Api _mtApi = null;

mt.Api mtApi() {
try {
if (!loggedIntoSocial())
throw Exception('Cannot get MT Api before logging in');
} catch (e, s) { print("$s"); throw Exception("$e"); }
if (_mtApi == null)
_mtApi = mt.Api(_accessToken());
return _mtApi;
if (!loggedIntoSocial())
throw Exception('Cannot get MT Api before logging in');
} catch (e, s) {
print("$s");
throw Exception("$e");
}
if (_mtApi == null) _mtApi = mt.Api(_accessToken());
return _mtApi;
}


// General things

SharedPreferences _prefs = null;
Expand Down Expand Up @@ -92,8 +91,7 @@ class LoginHandler extends ChangeNotifier {

int _userId = null;
Future<int> userId() async {
if (_userId == null)
_userId = await osmApi().userId();
if (_userId == null) _userId = await osmApi().userId();
return _userId;
}

Expand All @@ -102,11 +100,9 @@ class LoginHandler extends ChangeNotifier {
optIn() async {
print('Opting in to social features');
await prefs().setBool('socialOptIn', true);
await userId().then((id) =>
mtApi().createUser(id, _accessSecret(), _ckey, _csec).then((_) =>
notifyListeners()
)
);
await userId().then((id) => mtApi()
.createUser(id, _accessSecret(), _ckey, _csec)
.then((_) => notifyListeners()));
}

login(token, secret) async {
Expand Down
1 change: 0 additions & 1 deletion client/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:maptogether_api/maptogether_api.dart';


void main() => runApp(
MultiProvider(providers: [
ChangeNotifierProvider(create: (_) => LoginHandler()),
Expand Down
7 changes: 3 additions & 4 deletions client/lib/quests/bench_quest/backrest_bench_quest.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import 'package:latlong/latlong.dart';
import 'package:osm_api/osm_api.dart' as osm;

class BackrestBenchQuest extends Quest {

BackrestBenchQuest(LatLng position, osm.Element element) : super(position, element);
BackrestBenchQuest(LatLng position, osm.Element element)
: super(position, element);

@override
List<String> getPossibilities() {
Expand All @@ -20,5 +20,4 @@ class BackrestBenchQuest extends Quest {
String getChangesetComment() {
return 'Added backrest tag for bench';
}

}
}
2 changes: 1 addition & 1 deletion client/lib/quests/quest.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ abstract class Quest {
String getQuestion();

List<String> getPossibilities();
}
}
9 changes: 6 additions & 3 deletions client/lib/quests/quest_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,16 @@ class QuestHandler extends ChangeNotifier {
LoginHandler loginHandler,
LocationHandler locationHandler,
QuestHandler questFinder,
BackrestBenchQuest quest, int possibilityNumber,
BackrestBenchQuest quest,
int possibilityNumber,
) async {
var api = loginHandler.osmApi();

int changeSetId = await api.createChangeset(quest.getChangesetComment());

// add the new tag to the tag-map
quest.element.tags['backrest'] = quest.getPossibilities()[possibilityNumber].toString();
quest.element.tags['backrest'] =
quest.getPossibilities()[possibilityNumber].toString();

int nodeId = await api.updateNode(
quest.element.id,
Expand All @@ -69,7 +71,8 @@ class QuestHandler extends ChangeNotifier {
quest.element.tags);

api.closeChangeset(changeSetId);
print('Selected answer: ' + quest.getPossibilities()[possibilityNumber].toString());
print('Selected answer: ' +
quest.getPossibilities()[possibilityNumber].toString());

questFinder.getBenchQuests(
locationHandler.mapController.bounds.west,
Expand Down
38 changes: 18 additions & 20 deletions client/lib/screens/map_screen.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:latlong/latlong.dart';
Expand All @@ -17,10 +16,9 @@ import 'package:client/widgets/map/buttons/button_row.dart';
import 'package:client/widgets/map/buttons/map_screen_button.dart';
import 'package:client/widgets/map/buttons/pup_up_menu.dart';

launchSocial(BuildContext context) => Navigator.of(context)
.push(MaterialPageRoute(builder: (context) => SocialScreen()));

launchSocial(BuildContext context) =>
Navigator.of(context).push(MaterialPageRoute(builder: (context) => SocialScreen()));

class MapScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
Expand All @@ -45,13 +43,12 @@ class MapScreen extends StatelessWidget {
child: Icon(Icons.person),
onPressed: () {
//If no current user, go to login screen
if(loginHandler.loggedIntoSocial() != true)
if (loginHandler.loggedIntoSocial() != true)
requestLogin(context, social: true).then((r) {
if (r == true)
launchSocial(context);
});
if (r == true) launchSocial(context);
});
else
launchSocial(context);
launchSocial(context);
},
),
MapScreenButton(
Expand All @@ -64,18 +61,19 @@ class MapScreen extends StatelessWidget {
},
),
StreamBuilder(
stream: locationHandler.rotationStream,
builder: (BuildContext context, AsyncSnapshot<double> snapshot) =>
Transform.rotate(
angle: snapshot.data ?? 0,
child: MapScreenButton(
child: Icon(Icons.north),
onPressed: () {
locationHandler.mapController.rotate(0);
},
),
stream: locationHandler.rotationStream,
builder: (BuildContext context,
AsyncSnapshot<double> snapshot) =>
Transform.rotate(
angle: snapshot.data ?? 0,
child: MapScreenButton(
child: Icon(Icons.north),
onPressed: () {
locationHandler.mapController.rotate(0);
},
),
),
),
),
MapScreenButton(
child: Icon(Icons.wifi_protected_setup),
onPressed: () {
Expand Down
1 change: 0 additions & 1 deletion client/lib/screens/new_activity_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ class NewActivityScreen extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
appBar: MapTogetherAppBar(title: 'New Activity'),

);
}
}
23 changes: 12 additions & 11 deletions client/lib/screens/social_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,25 +24,26 @@ class _SocialScreenState extends State<SocialScreen> {

@override
Widget build(BuildContext context) {

if (user == null) {
user = context.read<LoginHandler>().user();
menuItems = [
Overview(user),
Friends(user),
Groups(),
History(),
user = context.read<LoginHandler>().user();
menuItems = [
Overview(user),
Friends(user),
Groups(),
History(),
];
}

return Scaffold(
appBar: MapTogetherAppBar(
title: 'Social',
actions: [
TextButton(child: Text("Log out", style: TextStyle(color: Colors.white)), onPressed: () {
context.read<LoginHandler>().logout();
Navigator.pop(context);
}),
TextButton(
child: Text("Log out", style: TextStyle(color: Colors.white)),
onPressed: () {
context.read<LoginHandler>().logout();
Navigator.pop(context);
}),
],
),
body: Container(
Expand Down
5 changes: 1 addition & 4 deletions client/lib/widgets/app_bar.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import 'package:flutter/material.dart';

class MapTogetherAppBar extends StatelessWidget implements PreferredSizeWidget {
MapTogetherAppBar(
{Key key,
@required this.title,
this.actions})
MapTogetherAppBar({Key key, @required this.title, this.actions})
: super(key: key);

String title;
Expand Down
20 changes: 12 additions & 8 deletions client/lib/widgets/error.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import 'package:flutter/material.dart';

class Error extends StatelessWidget {

final error;
Error(this.error) { print(this.error); }

Error(this.error) {
print(this.error);
}

@override
build(BuildContext context) =>
Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
);
Column(mainAxisAlignment: MainAxisAlignment.center, children: [
Icon(
Icons.error_outline,
color: Colors.red,
size: 60,
),
Text(error.toString()),
]);
}
Loading

0 comments on commit 34931e4

Please sign in to comment.