This repository has been archived by the owner on Feb 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
declarations.dart
219 lines (180 loc) · 6.84 KB
/
declarations.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
library coUserver;
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:logging/logging.dart' as rsLog;
import 'package:redstone_mapper/plugin.dart';
import 'package:redstone/redstone.dart' as app;
import 'package:path/path.dart';
import 'package:args/args.dart';
import 'package:coUserver/achievements/achievements.dart';
import 'package:coUserver/API_KEYS.dart';
import 'package:coUserver/auctions/auctions_service.dart';
import 'package:coUserver/buffs/buffmanager.dart';
import 'package:coUserver/common/api_helper.dart';
import 'package:coUserver/common/console.dart';
import 'package:coUserver/common/identifier.dart';
import 'package:coUserver/common/keep_alive.dart';
import 'package:coUserver/common/mapdata/mapdata.dart';
import 'package:coUserver/common/slack.dart';
import 'package:coUserver/common/user.dart';
import 'package:coUserver/common/util.dart';
import 'package:coUserver/endpoints/chat_handler.dart';
import 'package:coUserver/endpoints/metabolics/metabolics.dart';
import 'package:coUserver/endpoints/status.dart';
import 'package:coUserver/endpoints/weather/weather.dart';
import 'package:coUserver/entities/items/actions/recipes/recipe.dart';
import 'package:coUserver/entities/items/item.dart';
import 'package:coUserver/quests/quest.dart';
import 'package:coUserver/skills/skillsmanager.dart';
import 'package:coUserver/streets/player_update_handler.dart';
import 'package:coUserver/streets/street_update_handler.dart';
part 'package:coUserver/endpoints/elevation.dart';
part 'package:coUserver/endpoints/friends.dart';
part 'package:coUserver/endpoints/getitems.dart';
part 'package:coUserver/endpoints/report.dart';
part 'package:coUserver/endpoints/slack.dart';
part 'package:coUserver/endpoints/usernamecolors.dart';
part 'package:coUserver/endpoints/users.dart';
part 'package:coUserver/prerender_hack.dart';
// Port for app (redstone routing)
final int REDSTONE_PORT = 8181;
// Port for websocket listeners/handlers
final int WEBSOCKET_PORT = 8282;
bool loadCert = true;
// Start the server
Future main(List<String> arguments) async {
final parser = new ArgParser()
//use --no-load-cert to ignore certification loading
..addFlag("load-cert", defaultsTo: true, help: "Enables certificate loading for certificate");
ArgResults argResults = parser.parse(arguments);
loadCert = argResults['load-cert'];
try {
// Start logging
Log.init();
// Keep track of when the server was started
ServerStatus.serverStart = new DateTime.now();
Log.verbose('[Init] Server starting up');
// Start listening on REDSTONE_PORT
await _initRedstone();
// Start listening on WEBSOCKET_PORT
_initWebSockets();
// Refill energy on new day
MetabolicsEndpoint.trackNewDays();
// Run all of the loading functions at the same time for faster startup!
// This function will not return until all calls have finished, or an error is thrown.
await Future.wait([
// Load streets & hubs from JSON
MapData.load(),
// Load image caches
FileCache.loadCaches(),
// Load items, consume values, and vendor types from JSON
StreetUpdateHandler.loadItems(),
// Load quests from JSON
QuestService.loadQuests(),
// Load achievements from JSON
Achievement.load(),
// Load buffs from JSON
BuffManager.loadBuffs(),
// Load recipes from JSON
Recipe.load(),
// Load skills from JSON
SkillManager.loadSkills()
], eagerError: true);
// Enable interactive console
Console.init();
// String query = "SELECT * from users";
// String apiKeyQuery = "INSERT INTO api_access (api_token, user_id) values (@apiKey, @user_id)";
// PostgreSql dbConn = await dbManager.getConnection();
// List<User> users = await dbConn.query(query, User);
// await Future.forEach(users, (User user) async {
// Uuid uuid = new Uuid();
// String apiKey = uuid.v1();
// await dbConn.execute(apiKeyQuery, {'apiKey': apiKey, 'user_id': user.id});
// });
//load api access cache from the db
await API.loadApiAccess();
Log.info('[Init] Server started successfully, took ${ServerStatus.uptime}');
} catch (e, st) {
Log.error('[Init] Server startup failed', e, st);
cleanup(1);
}
}
// Add a CORS header to every request
@app.Interceptor(r'/.*', chainIdx: 0)
Future crossOriginInterceptor() async {
Map<String, String> header = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
};
if (app.request.method != 'OPTIONS') {
await app.chain.next();
}
return app.response.change(headers: header);
}
Future _initRedstone() async {
// Find port to bind
int port;
try {
port = int.parse(Platform.environment['PORT']);
} catch (error) {
port = REDSTONE_PORT;
}
// Initialize redstone
app.showErrorPage = false;
app.addPlugin(getMapperPlugin(dbManager));
app.setupConsoleLog(rsLog.Level.OFF);
if (loadCert) {
SecurityContext context = new SecurityContext()
..useCertificateChain('$certPath/fullchain.pem')
..usePrivateKey('$certPath/privkey.pem');
await app.start(port: port, autoCompress: true, secureOptions: {#context: context});
} else {
await app.start(port: port, autoCompress: true);
}
Log.verbose('[Init Redstone] Redstone initialized. REDSTONE LOGGING IS OFF.');
}
///This will serve up the needed files to animate the player characters
@app.Route('/getSpine')
Future<File> getSpine(@app.QueryParam() email, @app.QueryParam() filename) async {
File file = new File('./spineSkins/$email/$filename');
if (await file.exists()) {
return file;
} else {
return null;
}
}
/// redstone.dart does not support websockets so we have to listen on a separate port for those connections :(
Future _initWebSockets() async {
final Map<String, Function> _HANDLERS = {
'chat': ChatHandler.handle,
'metabolics': MetabolicsEndpoint.handle,
'playerUpdate': PlayerUpdateHandler.handle,
'quest': QuestEndpoint.handle,
'streetUpdate': StreetUpdateHandler.handle,
'weather': WeatherEndpoint.handle
};
HttpServer server;
if (loadCert) {
SecurityContext context = new SecurityContext()
..useCertificateChain('$certPath/fullchain.pem')
..usePrivateKey('$certPath/privkey.pem');
server = await HttpServer.bindSecure('0.0.0.0', WEBSOCKET_PORT, context);
} else {
Log.debug('[Init Websockets] Not loading cert');
server = await HttpServer.bind('0.0.0.0', WEBSOCKET_PORT);
}
server.listen((HttpRequest request) {
addToConnectionHistory(request.connectionInfo.remoteAddress);
WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
String handlerName = request.uri.path.replaceFirst('/', '');
_HANDLERS[handlerName](websocket);
}).catchError((error) {
Log.warning('Socket error', error);
}, test: (Exception e) => e is! WebSocketException)
.catchError((error) {}, test: (Exception e) => e is WebSocketException);
});
KeepAlive.start();
Log.verbose('[Init Websockets] WebSockets initialized');
}